init code

This commit is contained in:
Dmitry Chumak
2025-05-27 19:22:55 +05:00
parent 2b39909fd1
commit b47e0d3445
11 changed files with 529 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func AuthMiddleware(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
return []byte(secret), nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
// Add user ID to context
c.Set("userID", claims["sub"])
c.Set("username", claims["username"])
}
c.Next()
}
}