36 lines
878 B
Go
36 lines
878 B
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"photum-backend/internal/config"
|
|
)
|
|
|
|
func AuthMiddleware(cfg *config.Config) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
|
|
return
|
|
}
|
|
|
|
parts := strings.Split(authHeader, " ")
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header format"})
|
|
return
|
|
}
|
|
|
|
tokenString := parts[1]
|
|
claims, err := ValidateToken(tokenString, cfg.JwtAccessSecret)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
return
|
|
}
|
|
|
|
c.Set("userID", claims.UserID)
|
|
c.Set("role", claims.Role)
|
|
c.Next()
|
|
}
|
|
}
|