Private
Public Access
cambios en unificar los permisos de empresa con los gfenerales
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
7ba7d379ec
commit
f2cf7927eb
25 files changed
+104
-557
No files matched your search
@@ -2,7 +2,6 @@ package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
|
||||
@@ -62,7 +61,6 @@ func MigrarMultitenant() error {
|
||||
return err
|
||||
}
|
||||
|
||||
bootstrapPlataformaAdmin()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -145,36 +143,3 @@ func asegurarMembresias(empresaID uint) error {
|
||||
}
|
||||
return DB.Model(&primera).Update("rol", models_seguridad.RolOwner).Error
|
||||
}
|
||||
|
||||
func bootstrapPlataformaAdmin() {
|
||||
var count int64
|
||||
if err := DB.Model(&models_seguridad.PlataformaAdmin{}).Count(&count).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if count > 0 {
|
||||
return
|
||||
}
|
||||
|
||||
email := os.Getenv("SUPERADMIN_EMAIL")
|
||||
var usuario models_seguridad.Usuario
|
||||
if email != "" {
|
||||
if err := DB.Where("LOWER(email) = ?", email).First(&usuario).Error; err != nil {
|
||||
log.Printf("multitenant: SUPERADMIN_EMAIL %q no corresponde a ningún usuario", email)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if err := DB.Order("id ASC").First(&usuario).Error; err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := DB.Create(&models_seguridad.PlataformaAdmin{
|
||||
UsuarioID: usuario.ID,
|
||||
Rol: models_seguridad.RolSuperadmin,
|
||||
Activo: true,
|
||||
}).Error; err != nil {
|
||||
log.Printf("multitenant: no se pudo crear el superadmin inicial: %v", err)
|
||||
return
|
||||
}
|
||||
log.Printf("multitenant: usuario %s promovido a SUPERADMIN", usuario.Email)
|
||||
}
|
||||
@@ -101,8 +101,5 @@ func seleccionarEmpresa(usuarioID, empresaID uint, slug string) (uint, error) {
|
||||
return empresas[0].ID, nil
|
||||
}
|
||||
|
||||
if services.EsPlataformaAdmin(usuarioID) {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, services.ErrSinEmpresas
|
||||
}
|
||||
@@ -39,7 +39,6 @@ func Me(c *gin.Context) {
|
||||
Empresa: respuesta.Empresa,
|
||||
Empresas: respuesta.Empresas,
|
||||
EmpresaRol: respuesta.EmpresaRol,
|
||||
EsPlataformaAdmin: respuesta.EsPlataformaAdmin,
|
||||
Activo: respuesta.Usuario.Activo,
|
||||
DebeCambiarPassword: respuesta.DebeCambiarPassword,
|
||||
})
|
||||
@@ -57,9 +56,7 @@ func ObtenerMisEmpresas(c *gin.Context) {
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"empresas": empresas,
|
||||
"es_plataforma_admin": services.EsPlataformaAdmin(id),
|
||||
"rol_plataforma": services.RolPlataforma(id),
|
||||
"empresas": empresas,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -100,13 +97,12 @@ func ObtenerEmpresaActual(c *gin.Context) {
|
||||
miembros, _ := r.ObtenerRepositorios().Empresa.ContarMiembros(empresa.ID)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"id": empresa.ID,
|
||||
"nombre": empresa.Nombre,
|
||||
"slug": empresa.Slug,
|
||||
"cuit": empresa.Cuit,
|
||||
"activa": empresa.Activa,
|
||||
"rol": string(rol),
|
||||
"miembros_activos": miembros,
|
||||
"es_plataforma_admin": services.EsPlataformaAdmin(id),
|
||||
"id": empresa.ID,
|
||||
"nombre": empresa.Nombre,
|
||||
"slug": empresa.Slug,
|
||||
"cuit": empresa.Cuit,
|
||||
"activa": empresa.Activa,
|
||||
"rol": string(rol),
|
||||
"miembros_activos": miembros,
|
||||
})
|
||||
}
|
||||
@@ -72,12 +72,6 @@ func Register(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// En una instalación nueva, el primer usuario registrado es el
|
||||
// superadministrador de la plataforma. Los siguientes ya no.
|
||||
if total, err := repo.Empresa.ContarPlataformaAdmins(); err == nil && total == 0 {
|
||||
_ = repo.Empresa.AgregarPlataformaAdmin(user.ID, models_seguridad.RolSuperadmin)
|
||||
}
|
||||
|
||||
respuesta, err := services.ConstruirSesion(user.ID, empresa.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusCreated, dto.RegisterResponse{ID: user.ID, Email: user.Email, Name: user.Name})
|
||||
|
||||
@@ -361,14 +361,14 @@ func rolSolicitado(c *gin.Context, callerRol models_seguridad.RolEmpresa, solici
|
||||
return "", errors.New("rol inválido")
|
||||
}
|
||||
|
||||
if rol == models_seguridad.RolOwner && callerRol != models_seguridad.RolOwner && !utils.EsPlataformaAdmin(c) {
|
||||
if rol == models_seguridad.RolOwner && callerRol != models_seguridad.RolOwner {
|
||||
return "", errors.New("solo el owner puede asignar el rol OWNER")
|
||||
}
|
||||
return rol, nil
|
||||
}
|
||||
|
||||
func puedeModificarMiembro(c *gin.Context, callerRol, targetRol models_seguridad.RolEmpresa) error {
|
||||
if utils.EsPlataformaAdmin(c) || callerRol == models_seguridad.RolOwner {
|
||||
if callerRol == models_seguridad.RolOwner {
|
||||
return nil
|
||||
}
|
||||
if targetRol == models_seguridad.RolOwner {
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
package plataforma
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func ListarAdmins(c *gin.Context) {
|
||||
admins, err := r.ObtenerRepositorios().Empresa.ListarPlataformaAdmins()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"admins": admins})
|
||||
}
|
||||
|
||||
func AgregarAdmin(c *gin.Context) {
|
||||
var req struct {
|
||||
UsuarioID uint `json:"usuario_id"`
|
||||
Email string `json:"email"`
|
||||
Rol string `json:"rol"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios()
|
||||
var usuario *models_seguridad.Usuario
|
||||
var err error
|
||||
if req.UsuarioID != 0 {
|
||||
usuario, err = repo.Usuario.ObtenerPorID(req.UsuarioID)
|
||||
} else if strings.TrimSpace(req.Email) != "" {
|
||||
usuario, err = repo.Usuario.ObtenerPorEmail(strings.ToLower(strings.TrimSpace(req.Email)))
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Indicá usuario_id o email"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) || err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
rol := models_seguridad.RolPlataforma(strings.ToUpper(strings.TrimSpace(req.Rol)))
|
||||
if rol == "" {
|
||||
rol = models_seguridad.RolSuperadmin
|
||||
}
|
||||
if rol != models_seguridad.RolSuperadmin && rol != models_seguridad.RolSoporte {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Rol de plataforma inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.Empresa.AgregarPlataformaAdmin(usuario.ID, rol); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"message": "Rol de plataforma asignado", "usuario": usuario, "rol": rol})
|
||||
}
|
||||
|
||||
func QuitarAdmin(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios()
|
||||
total, err := repo.Empresa.ContarPlataformaAdmins()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if total <= 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Debe existir al menos un administrador de plataforma"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.Empresa.QuitarPlataformaAdmin(uint(id)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Rol de plataforma removido"})
|
||||
}
|
||||
|
||||
func ListarUsuarios(c *gin.Context) {
|
||||
pagina, _ := strconv.Atoi(c.DefaultQuery("p", "0"))
|
||||
tamano, _ := strconv.Atoi(c.DefaultQuery("s", "20"))
|
||||
|
||||
repo := r.ObtenerRepositorios()
|
||||
usuarios, total, err := repo.Usuario.ListarGlobales(pagina, tamano)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
respuesta := make([]gin.H, 0, len(usuarios))
|
||||
for _, usuario := range usuarios {
|
||||
rol := ""
|
||||
if admin, err := repo.Empresa.PlataformaAdminDe(usuario.ID); err == nil {
|
||||
rol = string(admin.Rol)
|
||||
}
|
||||
empresas, _ := repo.Empresa.ListarDeUsuario(usuario.ID)
|
||||
respuesta = append(respuesta, gin.H{
|
||||
"id": usuario.ID,
|
||||
"email": usuario.Email,
|
||||
"name": usuario.Name,
|
||||
"activo": usuario.Activo,
|
||||
"debe_cambiar_password": usuario.DebeCambiarPassword,
|
||||
"rol_plataforma": rol,
|
||||
"empresas": len(empresas),
|
||||
"created_at": usuario.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"usuarios": respuesta, "total": total})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package plataforma
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ListarUsuarios(c *gin.Context) {
|
||||
pagina, _ := strconv.Atoi(c.DefaultQuery("p", "0"))
|
||||
tamano, _ := strconv.Atoi(c.DefaultQuery("s", "20"))
|
||||
|
||||
repo := r.ObtenerRepositorios()
|
||||
usuarios, total, err := repo.Usuario.ListarGlobales(pagina, tamano)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
respuesta := make([]gin.H, 0, len(usuarios))
|
||||
for _, usuario := range usuarios {
|
||||
empresas, _ := repo.Empresa.ListarDeUsuario(usuario.ID)
|
||||
respuesta = append(respuesta, gin.H{
|
||||
"id": usuario.ID,
|
||||
"email": usuario.Email,
|
||||
"name": usuario.Name,
|
||||
"activo": usuario.Activo,
|
||||
"debe_cambiar_password": usuario.DebeCambiarPassword,
|
||||
"empresas": len(empresas),
|
||||
"created_at": usuario.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"usuarios": respuesta, "total": total})
|
||||
}
|
||||
@@ -11,7 +11,7 @@ func TestTokenRoundTrip(t *testing.T) {
|
||||
os.Setenv("JWTString", "test-secret")
|
||||
t.Cleanup(func() { os.Unsetenv("JWTString") })
|
||||
|
||||
token, err := GenerarToken(7, 3, "OWNER", false, "a@b.c", "Nombre", TokenTypeAccess, []uint{1, 2, 4}, time.Minute)
|
||||
token, err := GenerarToken(7, 3, "OWNER", "a@b.c", "Nombre", TokenTypeAccess, []uint{1, 2, 4}, time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("generar token: %v", err)
|
||||
}
|
||||
|
||||
+1
-60
@@ -63,7 +63,7 @@ func SesionMiddleware() gin.HandlerFunc {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
} else if !esPlataformaAdmin(userID) {
|
||||
} else {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "La sesión no tiene una empresa activa"})
|
||||
c.Abort()
|
||||
return
|
||||
@@ -74,28 +74,6 @@ func SesionMiddleware() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// 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))
|
||||
@@ -175,11 +153,6 @@ func cargarContexto(c *gin.Context, claims jwtutils.MapClaims, userID, empresaID
|
||||
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 {
|
||||
@@ -199,35 +172,3 @@ func membresiaActiva(usuarioID, empresaID uint) bool {
|
||||
}
|
||||
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 tenés permiso para realizar esta acción"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func PermisosMiddleware(permisosIDs ...uint) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !utils.UsuarioTieneAlgunPermiso(c, permisosIDs) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para realizar esta acción"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -42,12 +42,6 @@ type RepositorioEmpresa interface {
|
||||
ObtenerInvitacionPorToken(token string) (*models_seguridad.InvitacionEmpresa, error)
|
||||
MarcarInvitacionUsada(id uint) error
|
||||
EliminarInvitacion(empresaID, id uint) error
|
||||
|
||||
PlataformaAdminDe(usuarioID uint) (*models_seguridad.PlataformaAdmin, error)
|
||||
ListarPlataformaAdmins() ([]models_seguridad.PlataformaAdmin, error)
|
||||
ContarPlataformaAdmins() (int64, error)
|
||||
AgregarPlataformaAdmin(usuarioID uint, rol models_seguridad.RolPlataforma) error
|
||||
QuitarPlataformaAdmin(usuarioID uint) error
|
||||
}
|
||||
|
||||
type repositorioEmpresa struct {
|
||||
@@ -407,50 +401,6 @@ func (r *repositorioEmpresa) EliminarInvitacion(empresaID, id uint) error {
|
||||
Delete(&models_seguridad.InvitacionEmpresa{}).Error
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) PlataformaAdminDe(usuarioID uint) (*models_seguridad.PlataformaAdmin, error) {
|
||||
var admin models_seguridad.PlataformaAdmin
|
||||
if err := r.db.Where("usuario_id = ? AND activo = ?", usuarioID, true).
|
||||
First(&admin).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &admin, nil
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) ListarPlataformaAdmins() ([]models_seguridad.PlataformaAdmin, error) {
|
||||
var admins []models_seguridad.PlataformaAdmin
|
||||
err := r.db.Preload("Usuario").Order("created_at ASC").Find(&admins).Error
|
||||
return admins, err
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) ContarPlataformaAdmins() (int64, error) {
|
||||
var total int64
|
||||
err := r.db.Model(&models_seguridad.PlataformaAdmin{}).Where("activo = ?", true).Count(&total).Error
|
||||
return total, err
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) AgregarPlataformaAdmin(usuarioID uint, rol models_seguridad.RolPlataforma) error {
|
||||
if rol != models_seguridad.RolSuperadmin && rol != models_seguridad.RolSoporte {
|
||||
rol = models_seguridad.RolSuperadmin
|
||||
}
|
||||
var admin models_seguridad.PlataformaAdmin
|
||||
err := r.db.Where("usuario_id = ?", usuarioID).First(&admin).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return r.db.Create(&models_seguridad.PlataformaAdmin{
|
||||
UsuarioID: usuarioID,
|
||||
Rol: rol,
|
||||
Activo: true,
|
||||
}).Error
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.db.Model(&admin).Updates(map[string]any{"rol": rol, "activo": true}).Error
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) QuitarPlataformaAdmin(usuarioID uint) error {
|
||||
return r.db.Where("usuario_id = ?", usuarioID).Delete(&models_seguridad.PlataformaAdmin{}).Error
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) slugDisponible(slug, nombre string) string {
|
||||
base := config.Slugify(slug)
|
||||
if base == "" {
|
||||
|
||||
@@ -30,7 +30,6 @@ func main() {
|
||||
&models_seguridad.Permiso{},
|
||||
&models_seguridad.Grupo{},
|
||||
&models_seguridad.EmpresaUsuario{},
|
||||
&models_seguridad.PlataformaAdmin{},
|
||||
&models_seguridad.InvitacionEmpresa{},
|
||||
&models.Almacen{},
|
||||
&models.Marca{},
|
||||
|
||||
@@ -18,7 +18,7 @@ func PermisoRoute(r *gin.Engine) {
|
||||
}
|
||||
|
||||
escritura := r.Group("/permisos")
|
||||
escritura.Use(middleware.PlataformaMiddleware())
|
||||
escritura.Use(middleware.AuthMiddleware(8))
|
||||
{
|
||||
escritura.POST("", permiso.CrearPermiso)
|
||||
escritura.PUT("/:id", permiso.ActualizarPermiso)
|
||||
|
||||
@@ -9,17 +9,13 @@ import (
|
||||
|
||||
func PlataformaRoute(r *gin.Engine) {
|
||||
grupo := r.Group("/plataforma")
|
||||
grupo.Use(middleware.PlataformaMiddleware())
|
||||
grupo.Use(middleware.AuthMiddleware(8))
|
||||
{
|
||||
grupo.GET("/empresas", plataforma.ListarEmpresas)
|
||||
grupo.POST("/empresas", plataforma.CrearEmpresa)
|
||||
grupo.PUT("/empresas/:id", plataforma.ActualizarEmpresa)
|
||||
grupo.DELETE("/empresas/:id", plataforma.DesactivarEmpresa)
|
||||
|
||||
grupo.GET("/admins", plataforma.ListarAdmins)
|
||||
grupo.POST("/admins", plataforma.AgregarAdmin)
|
||||
grupo.DELETE("/admins/:id", plataforma.QuitarAdmin)
|
||||
|
||||
grupo.GET("/usuarios", plataforma.ListarUsuarios)
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ func EnviarEmail(mensaje MensajeEmail, creadorID uint) bool {
|
||||
}
|
||||
|
||||
token, err := jwtutils.GenerarToken(
|
||||
creadorID, 0, "", true, "", "repuestera", jwtutils.TokenTypeAccess, nil, 5*time.Minute,
|
||||
creadorID, 0, "", "", "repuestera", jwtutils.TokenTypeAccess, nil, 5*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return false
|
||||
|
||||
+33
-67
@@ -36,56 +36,41 @@ func ConstruirSesion(usuarioID, empresaID uint) (*dto.AuthResponse, error) {
|
||||
return nil, ErrUsuarioInactivo
|
||||
}
|
||||
|
||||
esPlataformaAdmin := EsPlataformaAdmin(usuarioID)
|
||||
|
||||
var (
|
||||
empresa *models_seguridad.Empresa
|
||||
empresaRol models_seguridad.RolEmpresa
|
||||
permisos []uint
|
||||
resumenEmpresa *dto.EmpresaResumen
|
||||
)
|
||||
|
||||
if empresaID == 0 {
|
||||
// Sesión de plataforma sin empresa activa. Solo es válida para
|
||||
// administradores de plataforma y no habilita datos de negocio.
|
||||
if !esPlataformaAdmin {
|
||||
return nil, ErrSinEmpresas
|
||||
}
|
||||
permisos = []uint{models_seguridad.PermisoPlataforma}
|
||||
} else {
|
||||
membresia, err := repo.Empresa.Membresia(empresaID, usuarioID)
|
||||
if err != nil || !membresia.Activo {
|
||||
return nil, ErrSinAcceso
|
||||
}
|
||||
return nil, ErrSinEmpresas
|
||||
}
|
||||
|
||||
empresa, err = repo.Empresa.ObtenerPorID(empresaID)
|
||||
if err != nil {
|
||||
return nil, ErrSinAcceso
|
||||
}
|
||||
if !empresa.Activa {
|
||||
return nil, ErrEmpresaInactiva
|
||||
}
|
||||
membresia, err := repo.Empresa.Membresia(empresaID, usuarioID)
|
||||
if err != nil || !membresia.Activo {
|
||||
return nil, ErrSinAcceso
|
||||
}
|
||||
|
||||
empresaRol = membresia.Rol
|
||||
permisos, err = PermisosDeMiembro(usuarioID, empresaID, membresia.Rol)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
empresa, err := repo.Empresa.ObtenerPorID(empresaID)
|
||||
if err != nil {
|
||||
return nil, ErrSinAcceso
|
||||
}
|
||||
if !empresa.Activa {
|
||||
return nil, ErrEmpresaInactiva
|
||||
}
|
||||
|
||||
resumenEmpresa = &dto.EmpresaResumen{
|
||||
ID: empresa.ID,
|
||||
Nombre: empresa.Nombre,
|
||||
Slug: empresa.Slug,
|
||||
Activa: empresa.Activa,
|
||||
Rol: string(membresia.Rol),
|
||||
}
|
||||
empresaRol := membresia.Rol
|
||||
permisos, err := PermisosDeMiembro(usuarioID, empresaID, membresia.Rol)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resumenEmpresa := &dto.EmpresaResumen{
|
||||
ID: empresa.ID,
|
||||
Nombre: empresa.Nombre,
|
||||
Slug: empresa.Slug,
|
||||
Activa: empresa.Activa,
|
||||
Rol: string(membresia.Rol),
|
||||
}
|
||||
|
||||
accessToken, err := jwtutils.GenerarToken(
|
||||
usuario.ID,
|
||||
empresaID,
|
||||
string(empresaRol),
|
||||
esPlataformaAdmin,
|
||||
usuario.Email,
|
||||
usuario.Name,
|
||||
jwtutils.TokenTypeAccess,
|
||||
@@ -100,7 +85,6 @@ func ConstruirSesion(usuarioID, empresaID uint) (*dto.AuthResponse, error) {
|
||||
usuario.ID,
|
||||
empresaID,
|
||||
string(empresaRol),
|
||||
esPlataformaAdmin,
|
||||
usuario.Email,
|
||||
usuario.Name,
|
||||
jwtutils.TokenTypeRefresh,
|
||||
@@ -117,15 +101,14 @@ func ConstruirSesion(usuarioID, empresaID uint) (*dto.AuthResponse, error) {
|
||||
}
|
||||
|
||||
return &dto.AuthResponse{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: int(AccessTokenDuration.Seconds()),
|
||||
Permissions: permisos,
|
||||
Empresa: resumenEmpresa,
|
||||
Empresas: empresas,
|
||||
EmpresaRol: string(empresaRol),
|
||||
EsPlataformaAdmin: esPlataformaAdmin,
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: int(AccessTokenDuration.Seconds()),
|
||||
Permissions: permisos,
|
||||
Empresa: resumenEmpresa,
|
||||
Empresas: empresas,
|
||||
EmpresaRol: string(empresaRol),
|
||||
Usuario: dto.UsuarioResumen{
|
||||
ID: usuario.ID,
|
||||
Email: usuario.Email,
|
||||
@@ -133,13 +116,9 @@ func ConstruirSesion(usuarioID, empresaID uint) (*dto.AuthResponse, error) {
|
||||
Activo: usuario.Activo,
|
||||
DebeCambiarPassword: usuario.DebeCambiarPassword,
|
||||
},
|
||||
DebeCambiarPassword: usuario.DebeCambiarPassword,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// PermisosDeMiembro calcula los permisos efectivos dentro de una empresa.
|
||||
// El owner siempre tiene todos los permisos de negocio de la empresa, incluso
|
||||
// si sus grupos fueron modificados.
|
||||
func PermisosDeMiembro(usuarioID, empresaID uint, rol models_seguridad.RolEmpresa) ([]uint, error) {
|
||||
usuario, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosDeEmpresa(usuarioID, empresaID)
|
||||
if err != nil {
|
||||
@@ -195,19 +174,6 @@ func EmpresaDeUsuario(usuarioID, empresaID uint) (*models_seguridad.Empresa, mod
|
||||
return empresa, membresia.Rol, nil
|
||||
}
|
||||
|
||||
func EsPlataformaAdmin(usuarioID uint) bool {
|
||||
admin, err := r.ObtenerRepositorios().Empresa.PlataformaAdminDe(usuarioID)
|
||||
return err == nil && admin != nil && admin.Activo
|
||||
}
|
||||
|
||||
func RolPlataforma(usuarioID uint) string {
|
||||
admin, err := r.ObtenerRepositorios().Empresa.PlataformaAdminDe(usuarioID)
|
||||
if err != nil || admin == nil || !admin.Activo {
|
||||
return ""
|
||||
}
|
||||
return string(admin.Rol)
|
||||
}
|
||||
|
||||
func anexarUnicos(base []uint, extras []uint) []uint {
|
||||
vistos := make(map[uint]bool, len(base)+len(extras))
|
||||
for _, id := range base {
|
||||
|
||||
@@ -12,8 +12,9 @@ import (
|
||||
// lista de IDs de permisos sin duplicados.
|
||||
func PermisosDeUsuario(usuario *models_seguridad.Usuario) []uint {
|
||||
permisosMap := make(map[uint]models_seguridad.Permiso)
|
||||
visitados := make(map[uint]bool)
|
||||
for i := range usuario.Grupos {
|
||||
usuario.Grupos[i].ListarPermisos(permisosMap)
|
||||
usuario.Grupos[i].ListarPermisos(permisosMap, visitados)
|
||||
}
|
||||
|
||||
permisos := make([]uint, 0, len(permisosMap))
|
||||
|
||||
+3
-14
@@ -5,10 +5,9 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
ContextPermissionsKey = "permissions"
|
||||
ContextEmpresaIDKey = "empresaID"
|
||||
ContextEmpresaRolKey = "empresaRol"
|
||||
ContextPlataformaAdmin = "esPlataformaAdmin"
|
||||
ContextPermissionsKey = "permissions"
|
||||
ContextEmpresaIDKey = "empresaID"
|
||||
ContextEmpresaRolKey = "empresaRol"
|
||||
)
|
||||
|
||||
// EmpresaID devuelve la empresa activa que dejo el middleware de auth.
|
||||
@@ -35,13 +34,3 @@ func EmpresaRol(c *gin.Context) string {
|
||||
rol, _ := value.(string)
|
||||
return rol
|
||||
}
|
||||
|
||||
// EsPlataformaAdmin indica si el usuario tiene un rol de plataforma.
|
||||
func EsPlataformaAdmin(c *gin.Context) bool {
|
||||
value, ok := c.Get(ContextPlataformaAdmin)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
es, _ := value.(bool)
|
||||
return es
|
||||
}
|
||||
@@ -138,7 +138,7 @@
|
||||
Mi empresa
|
||||
</a>
|
||||
{/if}
|
||||
{#if user.es_plataforma_admin}
|
||||
{#if user?.permissions?.includes(8)}
|
||||
<a
|
||||
href="/plataforma"
|
||||
class="flex w-full items-center gap-2 px-4 py-2.5 text-sm text-gray-300 no-underline transition-colors hover:bg-gray-700"
|
||||
|
||||
@@ -18,7 +18,6 @@ export function usuarioDesdeSesion(data: AuthResponse | MeResponse): Usuario {
|
||||
empresa: data.empresa ?? undefined,
|
||||
empresas: data.empresas,
|
||||
empresa_rol: data.empresa_rol,
|
||||
es_plataforma_admin: data.es_plataforma_admin,
|
||||
debe_cambiar_password: data.debe_cambiar_password
|
||||
};
|
||||
}
|
||||
@@ -29,8 +28,7 @@ export function usuarioDesdeSesion(data: AuthResponse | MeResponse): Usuario {
|
||||
permissions: me.permissions,
|
||||
empresa: me.empresa ?? undefined,
|
||||
empresas: me.empresas,
|
||||
empresa_rol: me.empresa_rol,
|
||||
es_plataforma_admin: me.es_plataforma_admin
|
||||
empresa_rol: me.empresa_rol
|
||||
};
|
||||
}
|
||||
|
||||
@@ -44,7 +42,6 @@ export function aplicarSesion(data: AuthResponse): void {
|
||||
empresa: data.empresa,
|
||||
empresas: data.empresas,
|
||||
empresa_rol: data.empresa_rol,
|
||||
es_plataforma_admin: data.es_plataforma_admin,
|
||||
usuario: data.usuario,
|
||||
debe_cambiar_password: data.debe_cambiar_password
|
||||
});
|
||||
@@ -62,7 +59,6 @@ export function aplicarMe(data: MeResponse): void {
|
||||
empresa: data.empresa ?? null,
|
||||
empresas: data.empresas,
|
||||
empresa_rol: data.empresa_rol,
|
||||
es_plataforma_admin: data.es_plataforma_admin,
|
||||
usuario: usuarioDesdeSesion(data),
|
||||
debe_cambiar_password: data.debe_cambiar_password
|
||||
});
|
||||
@@ -78,10 +74,6 @@ export function cerrarSesion(): void {
|
||||
notifyAuthChange();
|
||||
}
|
||||
|
||||
export function esPlataformaAdmin(): boolean {
|
||||
return getCurrentUser()?.es_plataforma_admin === true;
|
||||
}
|
||||
|
||||
export function empresaActual() {
|
||||
return getCurrentUser()?.empresa ?? getAuthTokens()?.empresa ?? null;
|
||||
}
|
||||
|
||||
@@ -7,8 +7,7 @@ import type {
|
||||
Invitacion,
|
||||
InvitacionCreada,
|
||||
InvitacionInfo,
|
||||
Miembro,
|
||||
PlataformaAdmin
|
||||
Miembro
|
||||
} from '../../types';
|
||||
import { aplicarSesion } from './session';
|
||||
|
||||
@@ -19,8 +18,6 @@ import { aplicarSesion } from './session';
|
||||
export async function obtenerMisEmpresas() {
|
||||
return apiFetch<{
|
||||
empresas: EmpresaResumen[];
|
||||
es_plataforma_admin: boolean;
|
||||
rol_plataforma: string;
|
||||
}>('/auth/empresas');
|
||||
}
|
||||
|
||||
@@ -173,22 +170,6 @@ export async function actualizarEmpresaPlataforma(
|
||||
return apiFetch<EmpresaPlataforma>(`/plataforma/empresas/${id}`, { method: 'PUT', body: dto });
|
||||
}
|
||||
|
||||
export async function listarAdminsPlataforma() {
|
||||
return apiFetch<{ admins: PlataformaAdmin[] }>('/plataforma/admins');
|
||||
}
|
||||
|
||||
export async function agregarAdminPlataforma(dto: {
|
||||
usuario_id?: number;
|
||||
email?: string;
|
||||
rol?: string;
|
||||
}) {
|
||||
return apiFetch('/plataforma/admins', { method: 'POST', body: dto });
|
||||
}
|
||||
|
||||
export async function quitarAdminPlataforma(usuarioID: number): Promise<void> {
|
||||
await apiFetch(`/plataforma/admins/${usuarioID}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export async function listarUsuariosGlobales(pagina = 0, tamano = 20) {
|
||||
return apiFetch<{
|
||||
usuarios: Array<{
|
||||
@@ -197,7 +178,6 @@ export async function listarUsuariosGlobales(pagina = 0, tamano = 20) {
|
||||
name: string;
|
||||
activo: boolean;
|
||||
debe_cambiar_password: boolean;
|
||||
rol_plataforma: string;
|
||||
empresas: number;
|
||||
created_at: string;
|
||||
}>;
|
||||
|
||||
@@ -9,7 +9,6 @@ export interface AuthTokens {
|
||||
empresa?: EmpresaResumen | null;
|
||||
empresas?: EmpresaResumen[];
|
||||
empresa_rol?: string;
|
||||
es_plataforma_admin?: boolean;
|
||||
usuario?: Usuario;
|
||||
debe_cambiar_password?: boolean;
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
<Text tag="p" type="body-long-01" color="secondary" class="py-8! text-center">
|
||||
{#if !usuario?.empresa}
|
||||
No tenés una empresa activa.
|
||||
{#if usuario?.es_plataforma_admin}
|
||||
{#if usuario?.permissions?.includes(8)}
|
||||
<a href="/plataforma">Ir a la administración de plataforma</a>
|
||||
{/if}
|
||||
{:else}
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
import { crearPermiso } from '$lib/hooks/crearPermiso';
|
||||
import { actualizarPermiso } from '$lib/hooks/actualizarPermiso';
|
||||
import { eliminarPermiso } from '$lib/hooks/eliminarPermiso';
|
||||
import { esPlataformaAdmin } from '$lib/hooks/session';
|
||||
import { getPermissions } from '$lib/hooks/token';
|
||||
import type { Permiso } from '../../types';
|
||||
import Add from 'carbon-icons-svelte/lib/Add.svelte';
|
||||
import Edit from 'carbon-icons-svelte/lib/Edit.svelte';
|
||||
@@ -32,8 +32,9 @@
|
||||
let permisos: Permiso[] = $state([]);
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
// El catálogo de permisos es global: solo plataforma puede editarlo.
|
||||
let puedeEditar = $state(esPlataformaAdmin());
|
||||
// El catálogo de permisos es global: solo quien tenga el permiso
|
||||
// de plataforma (8) puede editarlo.
|
||||
let puedeEditar = $state(getPermissions().includes(8));
|
||||
|
||||
let modalOpen = $state(false);
|
||||
let modalEditando = $state(false);
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
Modal,
|
||||
Pagination,
|
||||
PasswordInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
@@ -19,21 +17,17 @@
|
||||
Tag,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, Pen, TrashCan } from 'carbon-icons-svelte';
|
||||
import { Add, Pen } from 'carbon-icons-svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
actualizarEmpresaPlataforma,
|
||||
agregarAdminPlataforma,
|
||||
crearEmpresaPlataforma,
|
||||
listarAdminsPlataforma,
|
||||
listarEmpresasPlataforma,
|
||||
listarUsuariosGlobales,
|
||||
quitarAdminPlataforma
|
||||
listarUsuariosGlobales
|
||||
} from '$lib/hooks/tenant';
|
||||
import type { EmpresaPlataforma, PlataformaAdmin } from '../../types';
|
||||
import type { EmpresaPlataforma } from '../../types';
|
||||
|
||||
let empresas = $state<EmpresaPlataforma[]>([]);
|
||||
let admins = $state<PlataformaAdmin[]>([]);
|
||||
let usuarios = $state<Awaited<ReturnType<typeof listarUsuariosGlobales>>['usuarios']>([]);
|
||||
let totalUsuarios = $state(0);
|
||||
let paginaUsuarios = $state(0);
|
||||
@@ -57,11 +51,6 @@
|
||||
let errorEmpresa = $state('');
|
||||
let passwordTemporal = $state('');
|
||||
|
||||
let modalAdmin = $state(false);
|
||||
let formAdmin = $state({ email: '', rol: 'SUPERADMIN' });
|
||||
let guardandoAdmin = $state(false);
|
||||
let errorAdmin = $state('');
|
||||
|
||||
function aviso(mensaje: string) {
|
||||
exito = mensaje;
|
||||
setTimeout(() => (exito = ''), 4000);
|
||||
@@ -72,11 +61,6 @@
|
||||
empresas = res.empresas ?? [];
|
||||
}
|
||||
|
||||
async function cargarAdmins() {
|
||||
const res = await listarAdminsPlataforma();
|
||||
admins = res.admins ?? [];
|
||||
}
|
||||
|
||||
async function cargarUsuarios() {
|
||||
const res = await listarUsuariosGlobales(paginaUsuarios, tamanoUsuarios);
|
||||
usuarios = res.usuarios ?? [];
|
||||
@@ -87,7 +71,7 @@
|
||||
cargando = true;
|
||||
error = '';
|
||||
try {
|
||||
await Promise.all([cargarEmpresas(), cargarAdmins(), cargarUsuarios()]);
|
||||
await Promise.all([cargarEmpresas(), cargarUsuarios()]);
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo cargar la plataforma';
|
||||
} finally {
|
||||
@@ -174,40 +158,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
function abrirCrearAdmin() {
|
||||
formAdmin = { email: '', rol: 'SUPERADMIN' };
|
||||
errorAdmin = '';
|
||||
modalAdmin = true;
|
||||
}
|
||||
|
||||
async function guardarAdmin() {
|
||||
errorAdmin = '';
|
||||
guardandoAdmin = true;
|
||||
try {
|
||||
await agregarAdminPlataforma({ email: formAdmin.email, rol: formAdmin.rol });
|
||||
modalAdmin = false;
|
||||
await Promise.all([cargarAdmins(), cargarUsuarios()]);
|
||||
aviso('Administrador de plataforma agregado');
|
||||
} catch (e) {
|
||||
errorAdmin = e instanceof Error ? e.message : 'No se pudo agregar el administrador';
|
||||
} finally {
|
||||
guardandoAdmin = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function quitarAdmin(admin: PlataformaAdmin) {
|
||||
if (!confirm(`¿Quitar el rol de plataforma a ${admin.usuario?.email ?? `#${admin.usuario_id}`}?`)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await quitarAdminPlataforma(admin.usuario_id);
|
||||
await Promise.all([cargarAdmins(), cargarUsuarios()]);
|
||||
aviso('Rol de plataforma removido');
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'No se pudo remover el administrador';
|
||||
}
|
||||
}
|
||||
|
||||
async function cambiarPaginaUsuarios(nueva: number) {
|
||||
paginaUsuarios = nueva;
|
||||
try {
|
||||
@@ -295,52 +245,6 @@
|
||||
</TableContainer>
|
||||
</section>
|
||||
|
||||
<section class="mb-10">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 class="section-title mb-0!">Administradores de plataforma</h2>
|
||||
<Button size="small" icon={Add} onclick={abrirCrearAdmin}>Agregar admin</Button>
|
||||
</div>
|
||||
<TableContainer>
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Usuario</TableHeader>
|
||||
<TableHeader>Email</TableHeader>
|
||||
<TableHeader>Rol</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if admins.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={5}>No hay administradores</TableCell>
|
||||
</TableRow>
|
||||
{/if}
|
||||
{#each admins as admin (admin.usuario_id)}
|
||||
<TableRow>
|
||||
<TableCell>{admin.usuario?.name ?? `#${admin.usuario_id}`}</TableCell>
|
||||
<TableCell>{admin.usuario?.email ?? '-'}</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={admin.rol === 'SUPERADMIN' ? 'purple' : 'blue'}>{admin.rol}</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={admin.activo ? 'green' : 'red'}>
|
||||
{admin.activo ? 'Activo' : 'Inactivo'}
|
||||
</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button size="small" kind="danger" icon={TrashCan} onclick={() => quitarAdmin(admin)}>
|
||||
Quitar
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</section>
|
||||
|
||||
<section class="mb-10">
|
||||
<h2 class="section-title">Usuarios globales ({totalUsuarios})</h2>
|
||||
<TableContainer>
|
||||
@@ -351,14 +255,13 @@
|
||||
<TableHeader>Nombre</TableHeader>
|
||||
<TableHeader>Email</TableHeader>
|
||||
<TableHeader>Empresas</TableHeader>
|
||||
<TableHeader>Rol plataforma</TableHeader>
|
||||
<TableHeader>Estado</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if usuarios.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={6}>No hay usuarios</TableCell>
|
||||
<TableCell colspan={5}>No hay usuarios</TableCell>
|
||||
</TableRow>
|
||||
{/if}
|
||||
{#each usuarios as usuario (usuario.id)}
|
||||
@@ -367,7 +270,6 @@
|
||||
<TableCell>{usuario.name}</TableCell>
|
||||
<TableCell>{usuario.email}</TableCell>
|
||||
<TableCell>{usuario.empresas}</TableCell>
|
||||
<TableCell>{usuario.rol_plataforma || '-'}</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={usuario.activo ? 'green' : 'red'}>
|
||||
{usuario.activo ? 'Activo' : 'Inactivo'}
|
||||
@@ -433,29 +335,6 @@
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
bind:open={modalAdmin}
|
||||
modalHeading="Agregar administrador de plataforma"
|
||||
primaryButtonText="Agregar"
|
||||
secondaryButtonText="Cerrar"
|
||||
on:click:button--primary={guardarAdmin}
|
||||
on:click:button--secondary={() => (modalAdmin = false)}
|
||||
>
|
||||
{#if errorAdmin}
|
||||
<InlineNotification kind="error" title="Error" subtitle={errorAdmin} hideCloseButton />
|
||||
{/if}
|
||||
<div class="flex flex-col gap-4">
|
||||
<TextInput bind:value={formAdmin.email} labelText="Email del usuario" type="email" />
|
||||
<Select bind:selected={formAdmin.rol} labelText="Rol">
|
||||
<SelectItem value="SUPERADMIN" text="Superadmin" />
|
||||
<SelectItem value="SOPORTE" text="Soporte" />
|
||||
</Select>
|
||||
{#if guardandoAdmin}
|
||||
<InlineLoading description="Guardando..." />
|
||||
{/if}
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<style>
|
||||
.section-title {
|
||||
font-size: 1.05rem;
|
||||
|
||||
Vendored
-11
@@ -17,7 +17,6 @@ export interface Usuario {
|
||||
empresa?: EmpresaResumen;
|
||||
empresa_rol?: string;
|
||||
empresas?: EmpresaResumen[];
|
||||
es_plataforma_admin?: boolean;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
deleted_at?: string | null;
|
||||
@@ -32,7 +31,6 @@ export interface AuthResponse {
|
||||
empresa?: EmpresaResumen | null;
|
||||
empresas: EmpresaResumen[];
|
||||
empresa_rol: string;
|
||||
es_plataforma_admin: boolean;
|
||||
usuario: Usuario;
|
||||
debe_cambiar_password: boolean;
|
||||
}
|
||||
@@ -41,7 +39,6 @@ export interface MeResponse extends Usuario {
|
||||
permissions: number[];
|
||||
empresas: EmpresaResumen[];
|
||||
empresa_rol: string;
|
||||
es_plataforma_admin: boolean;
|
||||
}
|
||||
|
||||
export interface InvitacionInfo {
|
||||
@@ -88,7 +85,6 @@ export interface EmpresaActual {
|
||||
activa: boolean;
|
||||
rol: string;
|
||||
miembros_activos: number;
|
||||
es_plataforma_admin: boolean;
|
||||
}
|
||||
|
||||
export interface EmpresaPlataforma {
|
||||
@@ -102,13 +98,6 @@ export interface EmpresaPlataforma {
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
export interface PlataformaAdmin {
|
||||
usuario_id: number;
|
||||
rol: string;
|
||||
activo: boolean;
|
||||
usuario?: Usuario;
|
||||
}
|
||||
|
||||
export interface InvitacionCreada {
|
||||
invitacion: Invitacion;
|
||||
token: string;
|
||||
|
||||
Reference in new issue
Block a user