38 lines
1.3 KiB
Go
38 lines
1.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"kra/internal/biz"
|
|
"kra/internal/server/httpx"
|
|
"kra/internal/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func AccessControl(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
|
|
allowed, err := access.Authorize(c.Request.Context(), claims.AuthorityID, path, c.Request.Method)
|
|
if err != nil || !allowed {
|
|
requestID, _ := c.Get("request_id")
|
|
requestIDText, _ := requestID.(string)
|
|
_ = audit.RecordDataAccess(c.Request.Context(), &biz.DataAccessLog{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"})
|
|
c.AbortWithStatusJSON(http.StatusForbidden, httpx.Response{Code: httpx.CodeError, Data: nil, Msg: "权限不足"})
|
|
return
|
|
}
|
|
scope, err := access.ResolveDataScope(c.Request.Context(), claims.AuthorityID, claims.ID)
|
|
if err != nil {
|
|
httpx.Fail(c, "数据权限加载失败")
|
|
return
|
|
}
|
|
c.Request = c.Request.WithContext(biz.NewDataScopeContext(c.Request.Context(), scope))
|
|
c.Next()
|
|
}
|
|
}
|