This repository has been archived on 2024-11-28. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
schisandra-cloud-album/middleware/jwt.go
2024-08-19 23:10:15 +08:00

39 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middleware
import (
ginI18n "github.com/gin-contrib/i18n"
"github.com/gin-gonic/gin"
"schisandra-cloud-album/common/result"
"schisandra-cloud-album/global"
"schisandra-cloud-album/utils"
"strings"
)
func JWTAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 默认双Token放在请求头Authorization的Bearer中并以空格隔开
authHeader := c.GetHeader(global.CONFIG.JWT.HeaderKey)
if authHeader == "" {
c.Abort()
result.FailWithMessage(ginI18n.MustGetMessage(c, "AuthVerifyFailed"), c)
return
}
headerPrefix := global.CONFIG.JWT.HeaderPrefix
accessToken := strings.TrimPrefix(authHeader, headerPrefix+" ")
if accessToken == "" {
c.Abort()
result.FailWithMessage(ginI18n.MustGetMessage(c, "AuthVerifyFailed"), c)
return
}
parseToken, isUpd, err := utils.ParseAccessToken(accessToken)
if err != nil || !isUpd {
c.Abort()
result.FailWithCodeAndMessage(401, ginI18n.MustGetMessage(c, "AuthVerifyExpired"), c)
return
}
c.Set("userId", parseToken.UserID)
c.Next()
}
}