This commit is contained in:
2026-04-18 10:21:51 +03:00
commit 90d027025b
37 changed files with 6493 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
package auth
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func Middleware(jwtSecret string) gin.HandlerFunc {
return func(ctx *gin.Context) {
header := strings.TrimSpace(ctx.GetHeader("Authorization"))
if header == "" {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
return
}
parts := strings.SplitN(header, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
return
}
claims := &JWTClaims{}
token, err := jwt.ParseWithClaims(parts[1], 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(jwtSecret), nil
})
if err != nil || !token.Valid {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
ctx.Set("userID", claims.UserID)
ctx.Next()
}
}