You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.6 KiB
57 lines
1.6 KiB
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"laic-backend/cache"
|
|
"laic-backend/common"
|
|
"laic-backend/service"
|
|
"laic-backend/token"
|
|
)
|
|
|
|
// AuthMiddleware 鉴权中间件:解析 JWT + Redis 存证校验 + 会话校验。
|
|
func AuthMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
tokenString := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
|
|
if tokenString == "" {
|
|
common.FailWithBusiErrorWithHttpStatus(c, http.StatusUnauthorized, common.ErrUnauthorized)
|
|
return
|
|
}
|
|
claims, err := token.ParseToken(tokenString)
|
|
if err != nil {
|
|
common.FailWithBusiErrorWithHttpStatus(c, http.StatusUnauthorized, common.ErrToken)
|
|
return
|
|
}
|
|
storeKey := cache.UserTokenKeyOf(claims.UserID, token.GenerateShortID(tokenString))
|
|
if !common.HasKey(storeKey) || !service.DefaultUserService.SessionValid(claims.UserID, claims.SessionID, tokenString) {
|
|
common.FailWithBusiErrorWithHttpStatus(c, http.StatusUnauthorized, common.SignOutToken)
|
|
return
|
|
}
|
|
roles := claims.Roles
|
|
if roles == nil {
|
|
roles = []string{}
|
|
}
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("session_id", claims.SessionID)
|
|
c.Set("username", claims.Username)
|
|
c.Set("roles", roles)
|
|
c.Set("is_admin", slices.Contains(roles, common.RoleAdmin))
|
|
service.DefaultUserService.TouchSession(claims.UserID, claims.SessionID)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func AdminMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if !c.GetBool("is_admin") {
|
|
common.FailWithBusiErrorWithHttpStatus(c, http.StatusForbidden, common.ErrForbidden)
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|