44 lines
982 B
Go
44 lines
982 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"cockpit/internal/auth"
|
|
"cockpit/internal/domain"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const (
|
|
CtxUserIDKey = "userId"
|
|
CtxPermCodesKey = "permCodes"
|
|
)
|
|
|
|
func AuthRequired(authSvc *auth.Service) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
h := c.GetHeader("Authorization")
|
|
if h == "" || !strings.HasPrefix(h, "Bearer ") {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, domain.Fail("未登录"))
|
|
return
|
|
}
|
|
token := strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
|
|
claims, err := authSvc.ParseAccessToken(token)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, domain.Fail("登录已过期"))
|
|
return
|
|
}
|
|
|
|
perms, err := authSvc.GetUserPermCodes(c.Request.Context(), claims.UserID)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, domain.Fail("权限加载失败"))
|
|
return
|
|
}
|
|
|
|
c.Set(CtxUserIDKey, claims.UserID)
|
|
c.Set(CtxPermCodesKey, perms)
|
|
c.Next()
|
|
}
|
|
}
|
|
|