54 lines
1.9 KiB
Go
54 lines
1.9 KiB
Go
package middleware
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"kra/internal/biz"
|
|
"kra/internal/conf"
|
|
"kra/internal/server/httpx"
|
|
"kra/internal/service"
|
|
"kra/internal/service/dto"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func AccessControl(runtime *conf.Runtime, access *service.AccessService, audit *service.AuditService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
claims := Claims(c)
|
|
if claims == nil {
|
|
httpx.NoAuth(c, "未登录或非法访问")
|
|
return
|
|
}
|
|
path := c.Request.URL.Path
|
|
policyPath := path
|
|
if config := runtime.Admin(); config != nil && config.RouterPrefix != "" {
|
|
policyPath = strings.TrimPrefix(policyPath, strings.TrimSuffix(config.RouterPrefix, "/"))
|
|
if policyPath == "" {
|
|
policyPath = "/"
|
|
}
|
|
}
|
|
allowed, err := access.Authorize(c.Request.Context(), claims.AuthorityID, policyPath, c.Request.Method)
|
|
if err != nil || !allowed {
|
|
requestID, _ := c.Get("request_id")
|
|
requestIDText, _ := requestID.(string)
|
|
_ = audit.RecordDataAccessRequest(c.Request.Context(), &dto.DataAccessRecordRequest{EventType: "blocked_access", Operation: c.Request.Method, UserID: claims.ID, AuthorityID: claims.AuthorityID, RequestID: requestIDText, Method: c.Request.Method, Path: path, Detail: "Casbin policy denied the request"})
|
|
httpx.Write(c, httpx.CodeError, gin.H{}, "权限不足")
|
|
c.Abort()
|
|
return
|
|
}
|
|
requestContext, err := access.ContextWithDataScope(c.Request.Context(), claims.AuthorityID, claims.ID)
|
|
if err != nil {
|
|
requestContext = c.Request.Context()
|
|
}
|
|
if scope, ok := biz.DataScopeFromContext(requestContext); ok {
|
|
requestID, _ := c.Get("request_id")
|
|
scope.RequestID, _ = requestID.(string)
|
|
scope.Method, scope.Path = c.Request.Method, path
|
|
requestContext = biz.NewDataScopeContext(requestContext, scope)
|
|
}
|
|
requestContext = biz.NewActorContext(requestContext, biz.Actor{UserID: claims.ID, AuthorityID: claims.AuthorityID})
|
|
c.Request = c.Request.WithContext(requestContext)
|
|
c.Next()
|
|
}
|
|
}
|