57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"easywish/config"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
type Claims struct {
|
|
Username string `json:"username"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func JWTAuthMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
cfg := config.GetConfig()
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
|
|
return
|
|
}
|
|
|
|
tokenString := authHeader
|
|
|
|
token, err := jwt.ParseWithClaims(
|
|
tokenString,
|
|
&Claims{},
|
|
func(token *jwt.Token) (any, 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 {
|
|
if errors.Is(err, jwt.ErrTokenExpired) {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token expired"})
|
|
} else {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
|
|
}
|
|
return
|
|
}
|
|
|
|
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
|
c.Set("userID", claims.Username)
|
|
c.Next()
|
|
} else {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid claims"})
|
|
}
|
|
}
|
|
}
|