43 lines
1.0 KiB
Go
43 lines
1.0 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"gitea.zjmud.xyz/phyer/rbac/config"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func JWTAuthMiddleware() gin.HandlerFunc {
|
|
cfg := config.LoadConfig()
|
|
return func(c *gin.Context) {
|
|
tokenString := c.GetHeader("Authorization")
|
|
if tokenString == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header missing"})
|
|
return
|
|
}
|
|
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
|
}
|
|
return []byte(cfg.JWTSecret), nil
|
|
})
|
|
|
|
if err != nil || !token.Valid {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
|
|
return
|
|
}
|
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
if !ok {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims"})
|
|
return
|
|
}
|
|
|
|
c.Set("userID", claims["sub"])
|
|
c.Next()
|
|
}
|
|
}
|