56 lines
1.5 KiB
Go
56 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"base-framework/pkg/router"
|
|
"base-framework/pkg/utils"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func Auth() router.HandlerFunc {
|
|
return func(c *router.Context) {
|
|
tokenHeader := c.Header("Authorization")
|
|
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"})
|
|
return
|
|
}
|
|
|
|
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}"})
|
|
return
|
|
}
|
|
|
|
tokenStr := parts[1]
|
|
claims, err := utils.VerifyToken(tokenStr)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid token: " + err.Error()})
|
|
return
|
|
}
|
|
|
|
if claims.UserID != userIdHeader {
|
|
c.JSON(http.StatusUnauthorized, map[string]string{"error": "user_id does not match token"})
|
|
return
|
|
}
|
|
|
|
if claims.OrgID != orgIDHeader {
|
|
c.JSON(http.StatusUnauthorized, map[string]string{"error": "org_id does not match token"})
|
|
return
|
|
}
|
|
|
|
// 认证通过,继续执行后续中间件或处理器
|
|
c.Next()
|
|
}
|
|
}
|