72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
type Claims struct {
|
|
UserID int64 `json:"user_id"`
|
|
IsAdmin bool `json:"is_admin"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
|
if tokenString == authHeader {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization format"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(jwtSecret), nil
|
|
})
|
|
|
|
if err != nil || !token.Valid {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
claims, ok := token.Claims.(*Claims)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("is_admin", claims.IsAdmin)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func AdminMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
isAdmin, exists := c.Get("is_admin")
|
|
if !exists || !isAdmin.(bool) {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func GetUserID(c *gin.Context) int64 {
|
|
userID, _ := c.Get("user_id")
|
|
return userID.(int64)
|
|
}
|