38 lines
757 B
Go
38 lines
757 B
Go
package middleware
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"cloudnest/internal/pkg/jwt"
|
|
"cloudnest/internal/pkg/response"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func JWT(jwtSecret string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
auth := c.GetHeader("Authorization")
|
|
if !strings.HasPrefix(auth, "Bearer ") {
|
|
response.Unauthorized(c, "未提供认证令牌")
|
|
c.Abort()
|
|
return
|
|
}
|
|
tokenStr := strings.TrimPrefix(auth, "Bearer ")
|
|
|
|
claims, err := jwt.ParseToken(tokenStr, jwtSecret)
|
|
if err != nil {
|
|
response.Unauthorized(c, "令牌无效")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("username", claims.Username)
|
|
c.Set("user_code", claims.UserCode)
|
|
c.Next()
|
|
}
|
|
} |