Initial commit - cleaned for CV

This commit is contained in:
Renato97
2026-03-31 01:28:28 -03:00
commit ce9f0d5180
203 changed files with 50950 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/ren/econ/backend/internal/services"
)
func AuthMiddleware(authService *services.AuthService) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header requerido"})
c.Abort()
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Formato de authorization header inválido"})
c.Abort()
return
}
claims, err := authService.ValidateToken(parts[1])
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
c.Abort()
return
}
c.Set("user_id", claims.UserID)
c.Set("user_email", claims.Email)
c.Set("user_rol", claims.Rol)
c.Next()
}
}
func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
rol, exists := c.Get("user_rol")
if !exists || rol != "admin" {
c.JSON(http.StatusForbidden, gin.H{"error": "Acceso denegado - se requiere rol admin"})
c.Abort()
return
}
c.Next()
}
}