This commit is contained in:
oneao committed 2025-08-12 21:47:37 +08:00
1 parent 9af3234672
commit ed8bee3d77
11 files changed
+171 -57

No files matched your search

@@ -1,9 +1,12 @@
package middleware
import (
"base-framework/pkg/config"
"base-framework/pkg/router"
"base-framework/pkg/utils"
"net/http"
"base-framework/pkg/utils/response"
"errors"
"fmt"
"strings"
)
@@ -13,43 +16,50 @@ func Auth() router.HandlerFunc {
userIdHeader := c.Header("user_id")
orgIDHeader := c.Header("org_id")
if tokenHeader == "" {
c.JSON(http.StatusUnauthorized, map[string]string{"error": "Authorization header missing"})
return
}
if userIdHeader == "" {
c.JSON(http.StatusUnauthorized, map[string]string{"error": "user_id header missing"})
return
}
if orgIDHeader == "" {
c.JSON(http.StatusUnauthorized, map[string]string{"error": "org_id header missing"})
// 缺少登录信息
if tokenHeader == "" || userIdHeader == "" || orgIDHeader == "" {
response.Error(c).Code(response.CodeNoLogin).Send()
return
}
// Bearer token 格式校验
parts := strings.Fields(tokenHeader)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
c.JSON(http.StatusUnauthorized, map[string]string{"error": "Authorization header format must be Bearer {token}"})
if len(parts) != 2 || strings.ToLower(parts[0]) != "Bearer" {
response.Error(c).Code(response.CodeInvalidToken).Send()
return
}
// 解析 token
tokenStr := parts[1]
claims, err := utils.VerifyToken(tokenStr)
if err != nil {
c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid token: " + err.Error()})
switch {
case errors.Is(err, utils.ErrTokenExpired):
response.Error(c).Code(response.CodeLoginExpired).Send()
default:
response.Error(c).Code(response.CodeInvalidToken).Send()
}
return
}
// user_id 校验
if claims.UserID != userIdHeader {
c.JSON(http.StatusUnauthorized, map[string]string{"error": "user_id does not match token"})
response.Error(c).Code(response.CodeInvalidToken).Send()
return
}
// org_id 校验
if claims.OrgID != orgIDHeader {
c.JSON(http.StatusUnauthorized, map[string]string{"error": "org_id does not match token"})
response.Error(c).Code(response.CodeInvalidToken).Send()
return
}
// 认证通过,继续执行后续中间件或处理器
configs := config.GetDBConfigs()
for k := range configs {
fmt.Println(k)
}
c.Next()
}
}