Private
Public Access
primeros cambios hechos para tener el multitenant
This commit is contained in:
1 parent
34ad4424f9
commit
4e082e8767
132 files changed
+6202
-762
No files matched your search
+184
-41
@@ -4,58 +4,41 @@ 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 y, opcionalmente, exige que el usuario
|
||||
// tenga al menos uno de los permisos indicados. Los permisos viajan en el claim
|
||||
// "permissions" como una lista plana de IDs.
|
||||
// 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) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: Header Authorization no presente"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
partes := strings.Split(authHeader, " ")
|
||||
if len(partes) != 2 || partes[0] != "Bearer" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Formato de token invalido"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := jwtutils.ValidarTokenDeTipo(partes[1], jwtutils.TokenTypeAccess)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token invalido o expirado"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||
claims, userID, ok := validarAccessToken(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token invalido: usuario no encontrado"})
|
||||
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
|
||||
}
|
||||
|
||||
permisos := jwtutils.PermisosDesdeClaims(claims)
|
||||
c.Set("userID", userID)
|
||||
c.Set(utils.ContextPermissionsKey, permisos)
|
||||
if !membresiaActiva(userID, empresaID) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés acceso a esta empresa"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if email, ok := claims["email"].(string); ok {
|
||||
c.Set("email", email)
|
||||
}
|
||||
if name, ok := claims["name"].(string); ok {
|
||||
c.Set("name", name)
|
||||
}
|
||||
cargarContexto(c, claims, userID, empresaID)
|
||||
|
||||
if len(permisosRequeridos) > 0 && !utils.UsuarioTieneAlgunPermiso(c, permisosRequeridos) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para realizar esta accion"})
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para realizar esta acción"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -64,10 +47,173 @@ func AuthMiddleware(permisosRequeridos ...uint) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 if !esPlataformaAdmin(userID) {
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
// PlataformaMiddleware valida el rol transversal de plataforma. No habilita
|
||||
// por sí solo el acceso a datos de una empresa.
|
||||
func PlataformaMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
claims, userID, ok := validarAccessToken(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if !esPlataformaAdmin(userID) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permisos de plataforma"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
empresaID, _ := jwtutils.ClaimUint(claims, jwtutils.ClaimEmpresaID)
|
||||
cargarContexto(c, claims, userID, empresaID)
|
||||
c.Set(utils.ContextPlataformaAdmin, true)
|
||||
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, models_seguridad.PermisoGestionUsuarios) ||
|
||||
utils.UsuarioTienePermiso(c, models_seguridad.PermisoGestionEmpresa) {
|
||||
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)
|
||||
}
|
||||
|
||||
// Un rol de plataforma revocado en la base no debe seguir vigente hasta
|
||||
// que expire el token.
|
||||
plataforma := jwtutils.ClaimBool(claims, jwtutils.ClaimPlataformaAdmin) && esPlataformaAdmin(userID)
|
||||
c.Set(utils.ContextPlataformaAdmin, plataforma)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func esPlataformaAdmin(usuarioID uint) bool {
|
||||
var count int64
|
||||
if err := config.DB.Model(&models_seguridad.PlataformaAdmin{}).
|
||||
Where("usuario_id = ? AND activo = ?", usuarioID, true).
|
||||
Count(&count).Error; err != nil {
|
||||
return false
|
||||
}
|
||||
return count > 0
|
||||
}
|
||||
|
||||
func PermisoMiddleware(permisoID uint) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, permisoID) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para realizar esta accion"})
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para realizar esta acción"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -78,13 +224,10 @@ func PermisoMiddleware(permisoID uint) gin.HandlerFunc {
|
||||
func PermisosMiddleware(permisosIDs ...uint) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !utils.UsuarioTieneAlgunPermiso(c, permisosIDs) {
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
"error": "No tienes permiso para realizar esta accion",
|
||||
})
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para realizar esta acción"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user