30 lines
802 B
Go
30 lines
802 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"nl-pms-api/internal/commonservice"
|
|
)
|
|
|
|
// RequireJWT 校验 Authorization: Bearer <access token>,并把 user_id/username 写入上下文。
|
|
func RequireJWT(secret string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token := strings.TrimSpace(strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer "))
|
|
if token == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "UNAUTHORIZED"})
|
|
return
|
|
}
|
|
claims, err := commonservice.Parse(secret, token, "access")
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "UNAUTHORIZED"})
|
|
return
|
|
}
|
|
c.Set(commonservice.CtxUserID, claims.UserID)
|
|
c.Set(commonservice.CtxUsername, claims.Username)
|
|
c.Next()
|
|
}
|
|
}
|