38 lines
866 B
Go
38 lines
866 B
Go
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()
|
|
}
|
|
}
|
|
|