Private
Public Access
175 lines
4.8 KiB
Go
175 lines
4.8 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"repuestera_back/config"
|
|
"repuestera_back/jwtutils"
|
|
models_seguridad "repuestera_back/models/seguridad"
|
|
"repuestera_back/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// AuthMiddleware valida la firma del JWT, exige una empresa activa en el token
|
|
// y valida la membresía del usuario. Opcionalmente exige alguno de los
|
|
// permisos indicados.
|
|
func AuthMiddleware(permisosRequeridos ...uint) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
claims, userID, ok := validarAccessToken(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
empresaID, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimEmpresaID)
|
|
if !ok || empresaID == 0 {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido: empresa no seleccionada"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if !membresiaActiva(userID, empresaID) {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés acceso a esta empresa"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
cargarContexto(c, claims, userID, empresaID)
|
|
|
|
if len(permisosRequeridos) > 0 && !utils.UsuarioTieneAlgunPermiso(c, permisosRequeridos) {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para realizar esta acción"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// SesionMiddleware valida el token y deja el usuario en el contexto, pero
|
|
// permite sesiones de plataforma sin empresa activa (empresa_id = 0).
|
|
func SesionMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
claims, userID, ok := validarAccessToken(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
empresaID, _ := jwtutils.ClaimUint(claims, jwtutils.ClaimEmpresaID)
|
|
if empresaID != 0 {
|
|
if !membresiaActiva(userID, empresaID) {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés acceso a esta empresa"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
} else {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "La sesión no tiene una empresa activa"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
cargarContexto(c, claims, userID, empresaID)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RolEmpresaMiddleware restringe una ruta a determinados roles de la empresa.
|
|
func RolEmpresaMiddleware(roles ...models_seguridad.RolEmpresa) gin.HandlerFunc {
|
|
permitidos := make(map[string]bool, len(roles))
|
|
for _, rol := range roles {
|
|
permitidos[string(rol)] = true
|
|
}
|
|
|
|
return func(c *gin.Context) {
|
|
if !permitidos[utils.EmpresaRol(c)] {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "Tu rol en la empresa no permite esta acción"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// AdminEmpresaMiddleware acepta owners/admins o usuarios con permiso de
|
|
// gestión de usuarios/empresa.
|
|
func AdminEmpresaMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
rol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
|
if rol.EsAdministrador() ||
|
|
utils.UsuarioTienePermiso(c, 3) ||
|
|
utils.UsuarioTienePermiso(c, 7) {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para administrar la empresa"})
|
|
c.Abort()
|
|
}
|
|
}
|
|
|
|
func validarAccessToken(c *gin.Context) (jwtutils.MapClaims, uint, bool) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: Header Authorization no presente"})
|
|
c.Abort()
|
|
return nil, 0, false
|
|
}
|
|
|
|
partes := strings.Split(authHeader, " ")
|
|
if len(partes) != 2 || !strings.EqualFold(partes[0], "Bearer") {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Formato de token inválido"})
|
|
c.Abort()
|
|
return nil, 0, false
|
|
}
|
|
|
|
claims, err := jwtutils.ValidarTokenDeTipo(partes[1], jwtutils.TokenTypeAccess)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido o expirado"})
|
|
c.Abort()
|
|
return nil, 0, false
|
|
}
|
|
|
|
userID, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
|
if !ok || userID == 0 {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido: usuario no encontrado"})
|
|
c.Abort()
|
|
return nil, 0, false
|
|
}
|
|
|
|
return claims, userID, true
|
|
}
|
|
|
|
func cargarContexto(c *gin.Context, claims jwtutils.MapClaims, userID, empresaID uint) {
|
|
permisos := jwtutils.PermisosDesdeClaims(claims)
|
|
c.Set("userID", userID)
|
|
c.Set(utils.ContextEmpresaIDKey, empresaID)
|
|
c.Set(utils.ContextEmpresaRolKey, jwtutils.ClaimString(claims, jwtutils.ClaimEmpresaRol))
|
|
c.Set(utils.ContextPermissionsKey, permisos)
|
|
|
|
if email, ok := claims["email"].(string); ok {
|
|
c.Set("email", email)
|
|
}
|
|
if name, ok := claims["name"].(string); ok {
|
|
c.Set("name", name)
|
|
}
|
|
}
|
|
|
|
func membresiaActiva(usuarioID, empresaID uint) bool {
|
|
var count int64
|
|
if err := config.DB.Model(&models_seguridad.EmpresaUsuario{}).
|
|
Where("usuario_id = ? AND empresa_id = ? AND activo = ?", usuarioID, empresaID, true).
|
|
Count(&count).Error; err != nil {
|
|
return false
|
|
}
|
|
if count == 0 {
|
|
return false
|
|
}
|
|
|
|
var empresa models_seguridad.Empresa
|
|
if err := config.DB.First(&empresa, empresaID).Error; err != nil {
|
|
return false
|
|
}
|
|
return empresa.Activa
|
|
}
|