| package middleware |
|
|
| import ( |
| "net/http" |
| "strings" |
|
|
| "dinacom-11.0-backend/utils" |
|
|
| "github.com/gin-gonic/gin" |
| ) |
|
|
| func AuthMiddleware() gin.HandlerFunc { |
| return func(c *gin.Context) { |
| authHeader := c.GetHeader("Authorization") |
| if authHeader == "" { |
| c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"}) |
| return |
| } |
|
|
| var tokenString string |
| parts := strings.Split(authHeader, " ") |
| if len(parts) == 2 && parts[0] == "Bearer" { |
| tokenString = parts[1] |
| } else if len(parts) == 1 { |
| tokenString = parts[0] |
| } else { |
| c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid authorization header format"}) |
| return |
| } |
|
|
| claims, err := utils.ValidateToken(tokenString) |
| if err != nil { |
| c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"}) |
| return |
| } |
|
|
| |
| c.Set("user_id", claims.UserID) |
| c.Set("role", claims.Role) |
| c.Set("email", claims.Email) |
|
|
| c.Next() |
| } |
| } |
|
|
| func RoleMiddleware(allowedRoles ...string) gin.HandlerFunc { |
| return func(c *gin.Context) { |
| role, exists := c.Get("role") |
| if !exists { |
| c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) |
| return |
| } |
|
|
| userRole := role.(string) |
| for _, allowed := range allowedRoles { |
| if userRole == allowed { |
| c.Next() |
| return |
| } |
| } |
|
|
| c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Forbidden: insufficient permissions"}) |
| } |
| } |
|
|