A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.
fix(auth): add API key scope checks to enhance authorization security
LinkinStars6fc25c69f4ef
diff --git a/internal/base/middleware/auth.go b/internal/base/middleware/auth.goindex 7bfd5e7f..bb4cf255 100644--- a/internal/base/middleware/auth.go+++ b/internal/base/middleware/auth.go@@ -116,6 +116,10 @@ func (am *AuthUserMiddleware) MustAuthWithoutAccountAvailable() gin.HandlerFuncctx.Abort()return}+ // Check API key scope+ if am.AuthAPIKeyScope(ctx, token) {+ return+ }userInfo, err := am.authService.GetUserCacheInfo(ctx, token)if err != nil || userInfo == nil {handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil)@@ -141,6 +145,10 @@ func (am *AuthUserMiddleware) MustAuthAndAccountAvailable() gin.HandlerFunc {ctx.Abort()return}+ // Check API key scope+ if am.AuthAPIKeyScope(ctx, token) {+ return+ }userInfo, err := am.authService.GetUserCacheInfo(ctx, token)if err != nil || userInfo == nil {handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil)@@ -226,6 +234,26 @@ func (am *AuthUserMiddleware) CheckPrivateMode() gin.HandlerFunc {ctx.Next()}}++func (am *AuthUserMiddleware) AuthAPIKeyScope(ctx *gin.Context, accessToken string) (apiHaveNoScope bool) {+ if !strings.HasPrefix(accessToken, "sk_") {+ return false+ }+ var err error+ pass, err := am.authService.AuthAPIKey(ctx, ctx.Request.Method == "GET", accessToken)+ if err != nil {+ handler.HandleResponse(ctx, errors.Forbidden(reason.ForbiddenError), nil)+ ctx.Abort()+ return true+ }+ if !pass {+ handler.HandleResponse(ctx, errors.Forbidden(reason.ForbiddenError), nil)+ ctx.Abort()+ return true+ }+ return false+}+func ShowIndexPage(ctx *gin.Context) {ctx.Header("content-type", "text/html;charset=utf-8")ctx.Header("X-Frame-Options", "DENY")