Private
Public Access
primeros cambios hechos para tener el multitenant
This commit is contained in:
1 parent
34ad4424f9
commit
4e082e8767
132 files changed
+6014
-574
No files matched your search
@@ -0,0 +1,178 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// tablasTenant son las tablas de negocio que se filtran por empresa_id.
|
||||||
|
var tablasTenant = []string{
|
||||||
|
"groupos",
|
||||||
|
"almacen",
|
||||||
|
"marca",
|
||||||
|
"repuesto",
|
||||||
|
"stock",
|
||||||
|
"clientes",
|
||||||
|
"descuentos",
|
||||||
|
"forma_de_pago",
|
||||||
|
"proveedors",
|
||||||
|
"pago",
|
||||||
|
"logs",
|
||||||
|
"reservas",
|
||||||
|
"factura",
|
||||||
|
"recibo",
|
||||||
|
"remitos",
|
||||||
|
"nota_credito",
|
||||||
|
"nota_debito",
|
||||||
|
"orden_compra",
|
||||||
|
"devolucion",
|
||||||
|
"asiento_contables",
|
||||||
|
"movimiento_contables",
|
||||||
|
"cuenta_contables",
|
||||||
|
}
|
||||||
|
|
||||||
|
// MigrarMultitenant hace el backfill necesario para pasar de una instalación
|
||||||
|
// de una sola empresa a una base compartida con empresa_id. Es idempotente.
|
||||||
|
func MigrarMultitenant() error {
|
||||||
|
empresaID, err := empresaDefault()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tabla := range tablasTenant {
|
||||||
|
if !DB.Migrator().HasTable(tabla) || !DB.Migrator().HasColumn(tabla, "empresa_id") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := DB.Exec("UPDATE `"+tabla+"` SET empresa_id = ? WHERE empresa_id IS NULL OR empresa_id = 0", empresaID).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := migrarJoinAntiguo(); err != nil {
|
||||||
|
log.Printf("multitenant: no se pudo migrar el join antiguo usuario_grupos: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := asegurarMembresias(empresaID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
bootstrapPlataformaAdmin()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func empresaDefault() (uint, error) {
|
||||||
|
var empresa models_seguridad.Empresa
|
||||||
|
err := DB.Order("id ASC").First(&empresa).Error
|
||||||
|
if err == nil {
|
||||||
|
return empresa.ID, nil
|
||||||
|
}
|
||||||
|
if err != gorm.ErrRecordNotFound {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
empresa = models_seguridad.Empresa{
|
||||||
|
ID: 1,
|
||||||
|
Nombre: "Repuestera",
|
||||||
|
Slug: "repuestera",
|
||||||
|
Activa: true,
|
||||||
|
}
|
||||||
|
if err := DB.Create(&empresa).Error; err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return empresa.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrarJoinAntiguo() error {
|
||||||
|
if !DB.Migrator().HasTable("usuario_grupos") || !DB.Migrator().HasTable("usuarios_grupos") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return DB.Exec(
|
||||||
|
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) SELECT usuario_id, grupo_id FROM usuario_grupos",
|
||||||
|
).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// asegurarMembresias garantiza que todos los usuarios existentes tengan
|
||||||
|
// membresía en la empresa default. El primer usuario queda como OWNER.
|
||||||
|
func asegurarMembresias(empresaID uint) error {
|
||||||
|
var usuarios []models_seguridad.Usuario
|
||||||
|
if err := DB.Order("id ASC").Find(&usuarios).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, usuario := range usuarios {
|
||||||
|
var count int64
|
||||||
|
if err := DB.Model(&models_seguridad.EmpresaUsuario{}).
|
||||||
|
Where("empresa_id = ? AND usuario_id = ?", empresaID, usuario.ID).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if count > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
rol := models_seguridad.RolMiembro
|
||||||
|
if i == 0 {
|
||||||
|
rol = models_seguridad.RolOwner
|
||||||
|
}
|
||||||
|
if err := DB.Create(&models_seguridad.EmpresaUsuario{
|
||||||
|
EmpresaID: empresaID,
|
||||||
|
UsuarioID: usuario.ID,
|
||||||
|
Rol: rol,
|
||||||
|
Activo: true,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si no hay ningún owner, promover al usuario más antiguo de la empresa.
|
||||||
|
var owners int64
|
||||||
|
DB.Model(&models_seguridad.EmpresaUsuario{}).
|
||||||
|
Where("empresa_id = ? AND rol = ? AND activo = ?", empresaID, models_seguridad.RolOwner, true).
|
||||||
|
Count(&owners)
|
||||||
|
if owners > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var primera models_seguridad.EmpresaUsuario
|
||||||
|
if err := DB.Where("empresa_id = ?", empresaID).Order("usuario_id ASC").First(&primera).Error; err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MigrarAlmacen convierte la vieja tabla almacen (id varchar) al nuevo esquema
|
||||||
|
// con id numérico y codigo. Se ejecuta antes de AutoMigrate para que GORM no
|
||||||
|
// intente cambiar una PK referenciada por claves foráneas incompatibles.
|
||||||
|
func MigrarAlmacen() error {
|
||||||
|
if !DB.Migrator().HasTable("almacen") || !DB.Migrator().HasColumn("almacen", "id") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var tipo string
|
||||||
|
if err := DB.Raw(`
|
||||||
|
SELECT DATA_TYPE FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'almacen' AND COLUMN_NAME = 'id'
|
||||||
|
`).Scan(&tipo).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if tipo != "varchar" && tipo != "char" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("migrando almacen a id numérico...")
|
||||||
|
|
||||||
|
if err := DB.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer DB.Exec("SET FOREIGN_KEY_CHECKS = 1")
|
||||||
|
|
||||||
|
type fk struct {
|
||||||
|
Tabla string
|
||||||
|
Nombre string
|
||||||
|
}
|
||||||
|
var claves []fk
|
||||||
|
if err := DB.Raw(`
|
||||||
|
SELECT TABLE_NAME AS tabla, CONSTRAINT_NAME AS nombre
|
||||||
|
FROM information_schema.KEY_COLUMN_USAGE
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE()
|
||||||
|
AND REFERENCED_TABLE_NAME = 'almacen'
|
||||||
|
AND REFERENCED_COLUMN_NAME = 'id'
|
||||||
|
`).Scan(&claves).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, clave := range claves {
|
||||||
|
if err := DB.Exec(fmt.Sprintf(
|
||||||
|
"ALTER TABLE `%s` DROP FOREIGN KEY `%s`", clave.Tabla, clave.Nombre,
|
||||||
|
)).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tieneEmpresa := DB.Migrator().HasColumn("almacen", "empresa_id")
|
||||||
|
empresaExpr := "1"
|
||||||
|
if tieneEmpresa {
|
||||||
|
empresaExpr = "COALESCE(empresa_id, 1)"
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := DB.Exec("DROP TABLE IF EXISTS almacen_nuevo").Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := DB.Exec(`
|
||||||
|
CREATE TABLE almacen_nuevo (
|
||||||
|
id bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||||
|
empresa_id bigint unsigned NOT NULL DEFAULT 1,
|
||||||
|
codigo varchar(5) NOT NULL,
|
||||||
|
ubicacion varchar(40) NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_almacen_empresa_codigo (empresa_id, codigo)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||||
|
`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := DB.Exec(fmt.Sprintf(
|
||||||
|
"INSERT INTO almacen_nuevo (empresa_id, codigo, ubicacion) SELECT %s, id, ubicacion FROM almacen",
|
||||||
|
empresaExpr,
|
||||||
|
)).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := DB.Exec("DROP TABLE IF EXISTS tmp_almacen_map").Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := DB.Exec(`
|
||||||
|
CREATE TABLE tmp_almacen_map (
|
||||||
|
old_id varchar(5) NOT NULL,
|
||||||
|
new_id bigint unsigned NOT NULL
|
||||||
|
) ENGINE=InnoDB
|
||||||
|
`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := DB.Exec(`
|
||||||
|
INSERT INTO tmp_almacen_map (old_id, new_id)
|
||||||
|
SELECT a.id, n.id
|
||||||
|
FROM almacen a
|
||||||
|
JOIN almacen_nuevo n ON n.codigo = a.id AND n.empresa_id = ` + empresaExpr + `
|
||||||
|
`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if DB.Migrator().HasTable("stock") && DB.Migrator().HasColumn("stock", "almacen_id") {
|
||||||
|
if err := DB.Exec(`
|
||||||
|
UPDATE stock s JOIN tmp_almacen_map m ON s.almacen_id = m.old_id
|
||||||
|
SET s.almacen_id = m.new_id
|
||||||
|
`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if DB.Migrator().HasTable("reservas") && DB.Migrator().HasColumn("reservas", "almacen_id") {
|
||||||
|
if err := DB.Exec(`
|
||||||
|
UPDATE reservas r JOIN tmp_almacen_map m ON r.almacen_id = m.old_id
|
||||||
|
SET r.almacen_id = m.new_id
|
||||||
|
`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if DB.Migrator().HasTable("remitos") && DB.Migrator().HasColumn("remitos", "almacen_origen_id") {
|
||||||
|
if err := DB.Exec(`
|
||||||
|
UPDATE remitos r JOIN tmp_almacen_map m ON r.almacen_origen_id = m.old_id
|
||||||
|
SET r.almacen_origen_id = m.new_id
|
||||||
|
`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := DB.Exec("RENAME TABLE almacen TO almacen_viejo, almacen_nuevo TO almacen").Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := DB.Exec("DROP TABLE almacen_viejo").Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := DB.Exec("DROP TABLE tmp_almacen_map").Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("almacen migrado")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+188
-57
@@ -1,73 +1,204 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import models_seguridad "repuestera_back/models/seguridad"
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
func InitPermisos(){
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
var cantidadGrupos int64
|
|
||||||
DB.Model(&models_seguridad.Grupo{}).Count(&cantidadGrupos)
|
|
||||||
if (cantidadGrupos < 1) {
|
|
||||||
DB.Create(&models_seguridad.Grupo{
|
|
||||||
ID: 1,
|
|
||||||
Nombre: "Admin",
|
|
||||||
Descripcion: "Usuario Administrador Del sistema",
|
|
||||||
})
|
|
||||||
|
|
||||||
DB.Create(&models_seguridad.Grupo{
|
"gorm.io/gorm"
|
||||||
ID: 2,
|
)
|
||||||
Nombre: "Usuario",
|
|
||||||
Descripcion: "Usuario Común",
|
type permisoSemilla struct {
|
||||||
|
ID uint
|
||||||
|
Nombre string
|
||||||
|
Alias string
|
||||||
|
Descripcion string
|
||||||
|
}
|
||||||
|
|
||||||
|
var permisosSemilla = []permisoSemilla{
|
||||||
|
{1, "Gestión de Permisos", "permisos", "Administrar el catálogo global de permisos. Solo plataforma."},
|
||||||
|
{2, "Gestión de Grupos", "grupos", "Crear, editar y eliminar grupos de la empresa."},
|
||||||
|
{3, "Gestión de Usuarios", "usuarios", "Administrar miembros, invitaciones y cuentas de la empresa."},
|
||||||
|
{4, "Gestión de Repuestos", "repuestos", "Crear, editar y eliminar repuestos."},
|
||||||
|
{5, "Gestión de Logs", "logs", "Consultar la auditoría de la empresa."},
|
||||||
|
{6, "Gestión de Marcas", "marcas", "Crear, editar y eliminar marcas."},
|
||||||
|
{7, "Gestión de Empresa", "empresa", "Editar los datos de la empresa y sus miembros."},
|
||||||
|
{8, "Administración de Plataforma", "plataforma", "Administrar empresas y administradores globales."},
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitPermisos crea el catálogo global de permisos y garantiza que cada
|
||||||
|
// empresa tenga sus grupos base. Es idempotente.
|
||||||
|
func InitPermisos() {
|
||||||
|
for _, semilla := range permisosSemilla {
|
||||||
|
permiso := models_seguridad.Permiso{ID: semilla.ID}
|
||||||
|
DB.Where("id = ?", semilla.ID).FirstOrCreate(&permiso, models_seguridad.Permiso{
|
||||||
|
ID: semilla.ID,
|
||||||
|
Nombre: semilla.Nombre,
|
||||||
|
Alias: semilla.Alias,
|
||||||
|
Descripcion: semilla.Descripcion,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
var cantidadPermisos int64
|
var empresas []models_seguridad.Empresa
|
||||||
DB.Model(&models_seguridad.Permiso{}).Count(&cantidadPermisos)
|
if err := DB.Find(&empresas).Error; err != nil {
|
||||||
if (cantidadPermisos < 1){
|
return
|
||||||
permisos := []models_seguridad.Permiso{
|
|
||||||
{
|
|
||||||
ID: 1,
|
|
||||||
Nombre: "Gestion Permisos",
|
|
||||||
Descripcion: "Crear, Editar y Eliminar Permisos.",
|
|
||||||
Alias: "permisos",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
ID: 2,
|
|
||||||
Nombre: "Gestion Grupos",
|
|
||||||
Descripcion: "Crear, Editar y Eliminar Grupos.",
|
|
||||||
Alias: "grupos",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
ID: 3,
|
|
||||||
Nombre: "Gestion Usuarios",
|
|
||||||
Descripcion: "Crear, Modificar y Eliminar Cuentas de Usuario.",
|
|
||||||
Alias: "usuarios",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
ID: 4,
|
|
||||||
Nombre: "Gestionar Repuestos",
|
|
||||||
Descripcion: "Crear, Editar y Eliminar Repuestos.",
|
|
||||||
Alias: "repuesto",
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
DB.Create(&permisos)
|
for _, empresa := range empresas {
|
||||||
|
adminID, _, err := AsegurarGruposEmpresa(DB, empresa.ID)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
asegurarOwnersEnAdmin(DB, empresa.ID, adminID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var admin models_seguridad.Grupo
|
// AsegurarGruposEmpresa crea los grupos base "Admin" y "Usuario" de una
|
||||||
DB.First(&admin, 1)
|
// empresa y les asigna los permisos que corresponden. Devuelve sus IDs.
|
||||||
|
func AsegurarGruposEmpresa(db *gorm.DB, empresaID uint) (uint, uint, error) {
|
||||||
|
if empresaID == 0 {
|
||||||
|
return 0, 0, errors.New("empresa inválida")
|
||||||
|
}
|
||||||
|
|
||||||
DB.Model(&admin).Association("Permisos").Append(
|
admin, err := primerGrupo(db, empresaID, "Admin", "Administrador de la empresa")
|
||||||
&permisos[0],
|
if err != nil {
|
||||||
&permisos[1],
|
return 0, 0, err
|
||||||
&permisos[2],
|
}
|
||||||
)
|
usuario, err := primerGrupo(db, empresaID, "Usuario", "Usuario común de la empresa")
|
||||||
var usu models_seguridad.Grupo
|
if err != nil {
|
||||||
DB.First(&usu, 2)
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
DB.Model(&usu).Association("Permisos").Append(
|
permisosAdmin := []uint{
|
||||||
&permisos[3],
|
models_seguridad.PermisoGestionGrupos,
|
||||||
)
|
models_seguridad.PermisoGestionUsuarios,
|
||||||
|
models_seguridad.PermisoGestionRepuestos,
|
||||||
|
models_seguridad.PermisoGestionLogs,
|
||||||
|
models_seguridad.PermisoGestionMarcas,
|
||||||
|
models_seguridad.PermisoGestionEmpresa,
|
||||||
|
}
|
||||||
|
if err := asignarPermisosFaltantes(db, admin.ID, permisosAdmin); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
DB.Model(&admin).Association("Grupos").Append(
|
permisosUsuario := []uint{
|
||||||
&usu,
|
models_seguridad.PermisoGestionRepuestos,
|
||||||
|
models_seguridad.PermisoGestionMarcas,
|
||||||
|
}
|
||||||
|
if err := asignarPermisosFaltantes(db, usuario.ID, permisosUsuario); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return admin.ID, usuario.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func primerGrupo(db *gorm.DB, empresaID uint, nombre, descripcion string) (*models_seguridad.Grupo, error) {
|
||||||
|
grupo := models_seguridad.Grupo{}
|
||||||
|
err := db.Where("empresa_id = ? AND nombre = ?", empresaID, nombre).First(&grupo).Error
|
||||||
|
if err == nil {
|
||||||
|
return &grupo, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
grupo = models_seguridad.Grupo{
|
||||||
|
EmpresaID: empresaID,
|
||||||
|
Nombre: nombre,
|
||||||
|
Descripcion: descripcion,
|
||||||
|
}
|
||||||
|
if err := db.Create(&grupo).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &grupo, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func asignarPermisosFaltantes(db *gorm.DB, grupoID uint, ids []uint) error {
|
||||||
|
var actuales []models_seguridad.Permiso
|
||||||
|
if err := db.Model(&models_seguridad.Grupo{ID: grupoID}).Association("Permisos").Find(&actuales); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
existentes := make(map[uint]bool, len(actuales))
|
||||||
|
for _, permiso := range actuales {
|
||||||
|
existentes[permiso.ID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
var faltantes []models_seguridad.Permiso
|
||||||
|
for _, id := range ids {
|
||||||
|
if existentes[id] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var permiso models_seguridad.Permiso
|
||||||
|
if err := db.First(&permiso, id).Error; err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
faltantes = append(faltantes, permiso)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(faltantes) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return db.Model(&models_seguridad.Grupo{ID: grupoID}).Association("Permisos").Append(faltantes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func asegurarOwnersEnAdmin(db *gorm.DB, empresaID, adminID uint) {
|
||||||
|
var owners []models_seguridad.EmpresaUsuario
|
||||||
|
if err := db.Where("empresa_id = ? AND rol = ? AND activo = ?", empresaID, models_seguridad.RolOwner, true).
|
||||||
|
Find(&owners).Error; err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, owner := range owners {
|
||||||
|
var count int64
|
||||||
|
db.Table("usuarios_grupos").
|
||||||
|
Where("usuario_id = ? AND grupo_id = ?", owner.UsuarioID, adminID).
|
||||||
|
Count(&count)
|
||||||
|
if count > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
db.Exec(
|
||||||
|
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) VALUES (?, ?)",
|
||||||
|
owner.UsuarioID, adminID,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Slugify genera un slug estable a partir de un nombre.
|
||||||
|
func Slugify(nombre string) string {
|
||||||
|
nombre = strings.ToLower(strings.TrimSpace(nombre))
|
||||||
|
var b strings.Builder
|
||||||
|
guion := false
|
||||||
|
for _, r := range nombre {
|
||||||
|
switch {
|
||||||
|
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
|
||||||
|
b.WriteRune(r)
|
||||||
|
guion = false
|
||||||
|
case r == 'á' || r == 'à' || r == 'ä' || r == 'â':
|
||||||
|
b.WriteRune('a')
|
||||||
|
guion = false
|
||||||
|
case r == 'é' || r == 'è' || r == 'ë' || r == 'ê':
|
||||||
|
b.WriteRune('e')
|
||||||
|
guion = false
|
||||||
|
case r == 'í' || r == 'ì' || r == 'ï' || r == 'î':
|
||||||
|
b.WriteRune('i')
|
||||||
|
guion = false
|
||||||
|
case r == 'ó' || r == 'ò' || r == 'ö' || r == 'ô':
|
||||||
|
b.WriteRune('o')
|
||||||
|
guion = false
|
||||||
|
case r == 'ú' || r == 'ù' || r == 'ü' || r == 'û':
|
||||||
|
b.WriteRune('u')
|
||||||
|
guion = false
|
||||||
|
case r == 'ñ':
|
||||||
|
b.WriteRune('n')
|
||||||
|
guion = false
|
||||||
|
case r == ' ' || r == '-' || r == '_' || r == '.':
|
||||||
|
if !guion && b.Len() > 0 {
|
||||||
|
b.WriteRune('-')
|
||||||
|
guion = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Trim(b.String(), "-")
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/utils"
|
||||||
|
|
||||||
@@ -22,7 +23,7 @@ func CambiarContraseña(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(req.NewPassword) < 8 {
|
if len(req.NewPassword) < 8 {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "La nueva contraseña debe tener mas de 8 caracteres"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La nueva contraseña debe tener al menos 8 caracteres"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,30 +31,47 @@ func CambiarContraseña(c *gin.Context) {
|
|||||||
authUserIDUint, _ := authUserID.(uint)
|
authUserIDUint, _ := authUserID.(uint)
|
||||||
|
|
||||||
targetID := authUserIDUint
|
targetID := authUserIDUint
|
||||||
if req.UserID != 0 {
|
esPropia := req.UserID == 0 || req.UserID == authUserIDUint
|
||||||
|
if !esPropia {
|
||||||
targetID = req.UserID
|
targetID = req.UserID
|
||||||
}
|
}
|
||||||
|
|
||||||
esAdmin := utils.UsuarioTienePermiso(c, 3)
|
repo := r.ObtenerRepositorios()
|
||||||
|
user, err := repo.Usuario.ObtenerPorID(targetID)
|
||||||
if targetID != authUserIDUint && !esAdmin {
|
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para cambiar la contraseña de otro usuario"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(targetID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "usuario no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !esAdmin {
|
// Cambiar la contraseña propia siempre exige la contraseña actual.
|
||||||
|
if esPropia {
|
||||||
if req.OldPassword == "" {
|
if req.OldPassword == "" {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Se requiere la contraseña actual"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Se requiere la contraseña actual"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "contraseña actual incorrecta"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Contraseña actual incorrecta"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
rolCaller := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
|
||||||
|
esAdmin := utils.UsuarioTienePermiso(c, models_seguridad.PermisoGestionUsuarios) || rolCaller.EsAdministrador()
|
||||||
|
if !esAdmin {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para cambiar la contraseña de otro usuario"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
membresia, err := repo.Empresa.Membresia(empresaID, targetID)
|
||||||
|
if err != nil || !membresia.Activo {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solo un owner (o plataforma) puede resetear a otro administrador.
|
||||||
|
if !esPropia && rolCaller != models_seguridad.RolOwner && membresia.Rol.EsAdministrador() {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "Solo el owner puede cambiar la contraseña de un administrador"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,7 +82,8 @@ func CambiarContraseña(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Usuario.ActualizarContraseña(user.ID, string(hashedPassword)); err != nil {
|
// Un reset administrativo obliga al usuario a definir su propia clave.
|
||||||
|
if err := repo.Usuario.ActualizarContraseña(user.ID, string(hashedPassword), !esPropia); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al actualizar la contraseña"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al actualizar la contraseña"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/dto"
|
||||||
|
"repuestera_back/jwtutils"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ObtenerInvitacion es pública: permite mostrar los datos antes de aceptar.
|
||||||
|
func ObtenerInvitacion(c *gin.Context) {
|
||||||
|
token := strings.TrimSpace(c.Param("token"))
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
|
||||||
|
invitacion, err := repo.Empresa.ObtenerInvitacionPorToken(token)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Invitación no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
expirada := time.Now().After(invitacion.ExpiraEn)
|
||||||
|
usada := invitacion.UsadaEn != nil
|
||||||
|
_, errUsuario := repo.Usuario.ObtenerPorEmail(invitacion.Email)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, dto.InvitacionInfo{
|
||||||
|
Email: invitacion.Email,
|
||||||
|
Empresa: invitacion.Empresa.Nombre,
|
||||||
|
EmpresaID: invitacion.EmpresaID,
|
||||||
|
Rol: string(invitacion.Rol),
|
||||||
|
ExpiraEn: invitacion.ExpiraEn,
|
||||||
|
Valida: !expirada && !usada && invitacion.Empresa.Activa,
|
||||||
|
Usada: usada,
|
||||||
|
Expirada: expirada,
|
||||||
|
UsuarioExistente: errUsuario == nil,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// AceptarInvitacion suma al usuario a la empresa. Si la cuenta no existe, la
|
||||||
|
// crea con nombre y contraseña. Si ya existe, exige la contraseña actual (o
|
||||||
|
// una sesión válida del mismo usuario).
|
||||||
|
func AceptarInvitacion(c *gin.Context) {
|
||||||
|
token := strings.TrimSpace(c.Param("token"))
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
invitacion, err := repo.Empresa.ObtenerInvitacionPorToken(token)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Invitación no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if invitacion.UsadaEn != nil {
|
||||||
|
c.JSON(http.StatusGone, gin.H{"error": "La invitación ya fue utilizada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if time.Now().After(invitacion.ExpiraEn) {
|
||||||
|
c.JSON(http.StatusGone, gin.H{"error": "La invitación expiró"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !invitacion.Empresa.Activa {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "La empresa está deshabilitada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
email := strings.ToLower(strings.TrimSpace(invitacion.Email))
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
|
creado := false
|
||||||
|
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
if strings.TrimSpace(req.Name) == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El nombre es obligatorio"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(req.Password) < 8 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La contraseña debe tener al menos 8 caracteres"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
usuario = &models_seguridad.Usuario{
|
||||||
|
Email: email,
|
||||||
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Password: string(hash),
|
||||||
|
Activo: true,
|
||||||
|
}
|
||||||
|
if err := repo.Usuario.Crear(usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
creado = true
|
||||||
|
} else if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
if !usuario.Activo {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "La cuenta está deshabilitada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !sesionCorrespondeAlUsuario(c, usuario.ID) {
|
||||||
|
if req.Password == "" {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Ingresá tu contraseña para aceptar la invitación"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := bcrypt.CompareHashAndPassword([]byte(usuario.Password), []byte(req.Password)); err != nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Contraseña incorrecta"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.AgregarMiembro(invitacion.EmpresaID, usuario.ID, invitacion.Rol, invitacion.GrupoID); err != nil {
|
||||||
|
if creado {
|
||||||
|
_ = repo.Usuario.Eliminar(usuario.ID)
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.MarcarInvitacionUsada(invitacion.ID); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := services.ConstruirSesion(usuario.ID, invitacion.EmpresaID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"message": "Invitación aceptada",
|
||||||
|
"usuario_id": usuario.ID,
|
||||||
|
"empresa_id": invitacion.EmpresaID,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
status := http.StatusOK
|
||||||
|
if creado {
|
||||||
|
status = http.StatusCreated
|
||||||
|
}
|
||||||
|
c.JSON(status, respuesta)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sesionCorrespondeAlUsuario(c *gin.Context, usuarioID uint) bool {
|
||||||
|
header := c.GetHeader("Authorization")
|
||||||
|
partes := strings.Split(header, " ")
|
||||||
|
if len(partes) != 2 || !strings.EqualFold(partes[0], "Bearer") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
claims, err := jwtutils.ValidarTokenDeTipo(partes[1], jwtutils.TokenTypeAccess)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
sub, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||||
|
return ok && sub == usuarioID
|
||||||
|
}
|
||||||
@@ -4,66 +4,105 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"repuestera_back/dto"
|
|
||||||
"repuestera_back/jwtutils"
|
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/services"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Login(c *gin.Context) {
|
type loginRequest struct {
|
||||||
var req struct {
|
|
||||||
Email string `json:"email" binding:"required,email"`
|
Email string `json:"email" binding:"required,email"`
|
||||||
Password string `json:"password" binding:"required"`
|
Password string `json:"password" binding:"required"`
|
||||||
}
|
EmpresaID uint `json:"empresa_id"`
|
||||||
|
EmpresaSlug string `json:"empresa_slug"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Login(c *gin.Context) {
|
||||||
|
var req loginRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorEmail(email)
|
repo := r.ObtenerRepositorios()
|
||||||
|
user, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail Invalido"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail o contraseña inválidos"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Contrasena invalida"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail o contraseña inválidos"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
usuarioConPermisos, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(user.ID)
|
if !user.Activo {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "La cuenta está deshabilitada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID, err := seleccionarEmpresa(user.ID, req.EmpresaID, req.EmpresaSlug)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("login: no se pudieron cargar los permisos del usuario %d: %v", user.ID, err)
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "No se pudieron cargar los permisos del usuario"})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
permisos := utils.PermisosDeUsuario(usuarioConPermisos)
|
|
||||||
|
|
||||||
accessToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeAccess, permisos, 15*time.Minute)
|
respuesta, err := services.ConstruirSesion(user.ID, empresaID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("login: no se pudo generar el access token del usuario %d: %v", user.ID, err)
|
status := http.StatusForbidden
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
if err == services.ErrEmpresaInactiva {
|
||||||
|
status = http.StatusForbidden
|
||||||
|
}
|
||||||
|
if err == services.ErrSinEmpresas || err == services.ErrSinAcceso {
|
||||||
|
status = http.StatusForbidden
|
||||||
|
}
|
||||||
|
if err != services.ErrSinAcceso && err != services.ErrSinEmpresas && err != services.ErrEmpresaInactiva && err != services.ErrUsuarioInactivo {
|
||||||
|
log.Printf("login: error construyendo sesión del usuario %d: %v", user.ID, err)
|
||||||
|
status = http.StatusInternalServerError
|
||||||
|
}
|
||||||
|
c.JSON(status, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeRefresh, permisos, 24*time.Hour)
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
|
|
||||||
|
func seleccionarEmpresa(usuarioID, empresaID uint, slug string) (uint, error) {
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
|
||||||
|
if empresaID != 0 {
|
||||||
|
membresia, err := repo.Empresa.Membresia(empresaID, usuarioID)
|
||||||
|
if err != nil || !membresia.Activo {
|
||||||
|
return 0, services.ErrSinAcceso
|
||||||
|
}
|
||||||
|
return empresaID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if slug != "" {
|
||||||
|
empresa, err := repo.Empresa.ObtenerPorSlug(strings.TrimSpace(slug))
|
||||||
|
if err != nil {
|
||||||
|
return 0, services.ErrSinAcceso
|
||||||
|
}
|
||||||
|
membresia, err := repo.Empresa.Membresia(empresa.ID, usuarioID)
|
||||||
|
if err != nil || !membresia.Activo {
|
||||||
|
return 0, services.ErrSinAcceso
|
||||||
|
}
|
||||||
|
return empresa.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
empresas, err := services.ListarEmpresasDeUsuario(usuarioID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("login: no se pudo generar el refresh token del usuario %d: %v", user.ID, err)
|
return 0, err
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate refresh token"})
|
}
|
||||||
return
|
if len(empresas) > 0 {
|
||||||
}
|
return empresas[0].ID, nil
|
||||||
|
}
|
||||||
c.JSON(http.StatusOK, dto.TokenResponse{
|
|
||||||
AccessToken: accessToken,
|
if services.EsPlataformaAdmin(usuarioID) {
|
||||||
RefreshToken: refreshToken,
|
return 0, nil
|
||||||
TokenType: "Bearer",
|
}
|
||||||
ExpiresIn: 900,
|
return 0, services.ErrSinEmpresas
|
||||||
Permissions: permisos,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"repuestera_back/dto"
|
"repuestera_back/dto"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/utils"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -18,16 +20,93 @@ func Me(c *gin.Context) {
|
|||||||
|
|
||||||
id, ok := userID.(uint)
|
id, ok := userID.(uint)
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "token inválido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
permisos, _ := utils.PermisosDelContexto(c)
|
empresaID := utils.EmpresaID(c)
|
||||||
|
respuesta, err := services.ConstruirSesion(id, empresaID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.MeResponse{
|
c.JSON(http.StatusOK, dto.MeResponse{
|
||||||
ID: id,
|
ID: respuesta.Usuario.ID,
|
||||||
Email: c.GetString("email"),
|
Email: respuesta.Usuario.Email,
|
||||||
Name: c.GetString("name"),
|
Name: respuesta.Usuario.Name,
|
||||||
Permissions: permisos,
|
Permissions: respuesta.Permissions,
|
||||||
|
Empresa: respuesta.Empresa,
|
||||||
|
Empresas: respuesta.Empresas,
|
||||||
|
EmpresaRol: respuesta.EmpresaRol,
|
||||||
|
EsPlataformaAdmin: respuesta.EsPlataformaAdmin,
|
||||||
|
Activo: respuesta.Usuario.Activo,
|
||||||
|
DebeCambiarPassword: respuesta.DebeCambiarPassword,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ObtenerMisEmpresas devuelve las empresas donde el usuario es miembro.
|
||||||
|
func ObtenerMisEmpresas(c *gin.Context) {
|
||||||
|
userID, _ := c.Get("userID")
|
||||||
|
id, _ := userID.(uint)
|
||||||
|
|
||||||
|
empresas, err := services.ListarEmpresasDeUsuario(id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"empresas": empresas,
|
||||||
|
"es_plataforma_admin": services.EsPlataformaAdmin(id),
|
||||||
|
"rol_plataforma": services.RolPlataforma(id),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CambiarEmpresa emite una sesión nueva para otra empresa del usuario.
|
||||||
|
func CambiarEmpresa(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
EmpresaID uint `json:"empresa_id" binding:"required"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userID, _ := c.Get("userID")
|
||||||
|
id, _ := userID.(uint)
|
||||||
|
|
||||||
|
respuesta, err := services.ConstruirSesion(id, req.EmpresaID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ObtenerEmpresaActual devuelve los datos de la empresa activa.
|
||||||
|
func ObtenerEmpresaActual(c *gin.Context) {
|
||||||
|
userID, _ := c.Get("userID")
|
||||||
|
id, _ := userID.(uint)
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
|
||||||
|
empresa, rol, err := services.EmpresaDeUsuario(id, empresaID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -3,12 +3,10 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
|
||||||
|
|
||||||
"repuestera_back/dto"
|
|
||||||
"repuestera_back/jwtutils"
|
"repuestera_back/jwtutils"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/services"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -24,43 +22,34 @@ func Refresh(c *gin.Context) {
|
|||||||
|
|
||||||
claims, err := jwtutils.ValidarTokenDeTipo(req.RefreshToken, jwtutils.TokenTypeRefresh)
|
claims, err := jwtutils.ValidarTokenDeTipo(req.RefreshToken, jwtutils.TokenTypeRefresh)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid refresh token"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "refresh token inválido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sub, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
sub, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "refresh token inválido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(sub)
|
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(sub)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("refresh: no se pudo cargar el usuario %d: %v", sub, err)
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "usuario no encontrado"})
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
return
|
||||||
|
}
|
||||||
|
if !user.Activo {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "la cuenta está deshabilitada"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
permisos := utils.PermisosDeUsuario(user)
|
|
||||||
|
|
||||||
accessToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeAccess, permisos, 15*time.Minute)
|
empresaID, _ := jwtutils.ClaimUint(claims, jwtutils.ClaimEmpresaID)
|
||||||
|
|
||||||
|
respuesta, err := services.ConstruirSesion(user.ID, empresaID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("refresh: no se pudo generar el access token del usuario %d: %v", user.ID, err)
|
log.Printf("refresh: no se pudo renovar la sesión del usuario %d: %v", user.ID, err)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
newRefreshToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeRefresh, permisos, 24*time.Hour)
|
c.JSON(http.StatusOK, respuesta)
|
||||||
if err != nil {
|
|
||||||
log.Printf("refresh: no se pudo generar el refresh token del usuario %d: %v", user.ID, err)
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate refresh token"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.TokenResponse{
|
|
||||||
AccessToken: accessToken,
|
|
||||||
RefreshToken: newRefreshToken,
|
|
||||||
TokenType: "Bearer",
|
|
||||||
ExpiresIn: 900,
|
|
||||||
Permissions: permisos,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"repuestera_back/dto"
|
"repuestera_back/dto"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
@@ -15,8 +16,11 @@ import (
|
|||||||
func Register(c *gin.Context) {
|
func Register(c *gin.Context) {
|
||||||
var req struct {
|
var req struct {
|
||||||
Email string `json:"email" binding:"required,email"`
|
Email string `json:"email" binding:"required,email"`
|
||||||
Password string `json:"password" binding:"required,min=6"`
|
Password string `json:"password" binding:"required,min=8"`
|
||||||
Name string `json:"name" binding:"required"`
|
Name string `json:"name" binding:"required"`
|
||||||
|
EmpresaNombre string `json:"empresa_nombre"`
|
||||||
|
EmpresaSlug string `json:"empresa_slug"`
|
||||||
|
EmpresaCuit string `json:"empresa_cuit"`
|
||||||
}
|
}
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
@@ -24,44 +28,61 @@ func Register(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
|
||||||
if _, err := r.ObtenerRepositorios().Usuario.ObtenerPorEmail(email); err == nil {
|
if _, err := repo.Usuario.ObtenerPorEmail(email); err == nil {
|
||||||
c.JSON(http.StatusConflict, gin.H{"error": "El email ya esta registrado"})
|
c.JSON(http.StatusConflict, gin.H{"error": "El email ya está registrado"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contrasena"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user := models_seguridad.Usuario{
|
user := models_seguridad.Usuario{
|
||||||
Email: email,
|
Email: email,
|
||||||
Password: string(hashedPassword),
|
Password: string(hashedPassword),
|
||||||
Name: req.Name,
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Activo: true,
|
||||||
}
|
}
|
||||||
|
if err := repo.Usuario.Crear(&user); err != nil {
|
||||||
//checkeo para ver si hay usuarios añadidos
|
|
||||||
var cantUsuarios int64
|
|
||||||
r.ObtenerRepositorios().Usuario.CantidadUsuarios(&cantUsuarios)
|
|
||||||
if (cantUsuarios < 1){
|
|
||||||
admin, err := r.ObtenerRepositorios().Grupo.ObtenerPorID(1)
|
|
||||||
if err != nil{
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Hay un problema con la base de datos: Faltan Grupos?"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user.Grupos = append(user.Grupos, *admin)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Usuario.Crear(&user); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, dto.RegisterResponse{
|
nombreEmpresa := strings.TrimSpace(req.EmpresaNombre)
|
||||||
ID: user.ID,
|
if nombreEmpresa == "" {
|
||||||
Email: user.Email,
|
nombreEmpresa = "Empresa de " + user.Name
|
||||||
Name: user.Name,
|
}
|
||||||
})
|
empresa := models_seguridad.Empresa{
|
||||||
|
Nombre: nombreEmpresa,
|
||||||
|
Slug: req.EmpresaSlug,
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.EmpresaCuit) != "" {
|
||||||
|
cuit := strings.TrimSpace(req.EmpresaCuit)
|
||||||
|
empresa.Cuit = &cuit
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.Crear(&empresa, user.ID); err != nil {
|
||||||
|
// Si falla la creación de la empresa no dejamos una cuenta huérfana.
|
||||||
|
_ = repo.Usuario.Eliminar(user.ID)
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
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})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package empresa
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ListarInvitaciones(c *gin.Context) {
|
||||||
|
invitaciones, err := r.ObtenerRepositorios().Empresa.ListarInvitaciones(utils.EmpresaID(c))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"invitaciones": invitaciones})
|
||||||
|
}
|
||||||
|
|
||||||
|
func CrearInvitacion(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Email string `json:"email" binding:"required,email"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
GrupoID uint `json:"grupo_id"`
|
||||||
|
ExpiraHoras int `json:"expira_horas"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
rol, err := rolSolicitado(c, callerRol, req.Rol)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.GrupoID > 0 {
|
||||||
|
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorID(req.GrupoID)
|
||||||
|
if err != nil || grupo.EmpresaID != empresaID {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Grupo inválido para la empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
|
if err == nil {
|
||||||
|
if _, err := repo.Empresa.Membresia(empresaID, usuario.ID); err == nil {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "El usuario ya pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
expira := time.Now().Add(7 * 24 * time.Hour)
|
||||||
|
if req.ExpiraHoras > 0 {
|
||||||
|
if req.ExpiraHoras > 24*30 {
|
||||||
|
req.ExpiraHoras = 24 * 30
|
||||||
|
}
|
||||||
|
expira = time.Now().Add(time.Duration(req.ExpiraHoras) * time.Hour)
|
||||||
|
}
|
||||||
|
|
||||||
|
userID, _ := c.Get("userID")
|
||||||
|
creadorID, _ := userID.(uint)
|
||||||
|
|
||||||
|
invitacion := models_seguridad.InvitacionEmpresa{
|
||||||
|
EmpresaID: empresaID,
|
||||||
|
Email: email,
|
||||||
|
Rol: rol,
|
||||||
|
GrupoID: req.GrupoID,
|
||||||
|
ExpiraEn: expira,
|
||||||
|
CreadaPor: creadorID,
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := repo.Empresa.CrearInvitacion(&invitacion)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresa, err := repo.Empresa.ObtenerPorID(empresaID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
link := construirLinkInvitacion(token)
|
||||||
|
enviado := services.EnviarEmailInvitacion(email, empresa.Nombre, string(rol), link, creadorID)
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, gin.H{
|
||||||
|
"invitacion": invitacion,
|
||||||
|
"token": token,
|
||||||
|
"link": link,
|
||||||
|
"email_enviado": enviado,
|
||||||
|
"expira_en": invitacion.ExpiraEn,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func EliminarInvitacion(c *gin.Context) {
|
||||||
|
parsed, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios().Empresa.EliminarInvitacion(utils.EmpresaID(c), uint(parsed)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Invitación cancelada"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func construirLinkInvitacion(token string) string {
|
||||||
|
base := strings.TrimRight(os.Getenv("APP_URL"), "/")
|
||||||
|
if base == "" {
|
||||||
|
base = "http://localhost:3000"
|
||||||
|
}
|
||||||
|
return base + "/invitaciones/" + token
|
||||||
|
}
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
package empresa
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repuestera_back/dto"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type rolRequest struct {
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ObtenerMiembros(c *gin.Context) {
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
pagina, _ := strconv.Atoi(c.DefaultQuery("p", "0"))
|
||||||
|
tamano, _ := strconv.Atoi(c.DefaultQuery("s", "10"))
|
||||||
|
|
||||||
|
miembros, total, err := r.ObtenerRepositorios().Empresa.ListarMiembros(empresaID, pagina, tamano)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta := make([]dto.MiembroResponse, 0, len(miembros))
|
||||||
|
for _, miembro := range miembros {
|
||||||
|
respuesta = append(respuesta, dto.MiembroResponse{
|
||||||
|
ID: miembro.Usuario.ID,
|
||||||
|
Email: miembro.Usuario.Email,
|
||||||
|
Name: miembro.Usuario.Name,
|
||||||
|
Activo: miembro.Usuario.Activo,
|
||||||
|
DebeCambiarPassword: miembro.Usuario.DebeCambiarPassword,
|
||||||
|
Rol: string(miembro.Rol),
|
||||||
|
MembresiaActiva: miembro.Activo,
|
||||||
|
CreatedAt: miembro.Usuario.CreatedAt,
|
||||||
|
UpdatedAt: miembro.Usuario.UpdatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"usuarios": respuesta,
|
||||||
|
"miembros": respuesta,
|
||||||
|
"total": total,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ObtenerMiembro(c *gin.Context) {
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
miembro, err := r.ObtenerRepositorios().Empresa.Membresia(empresaID, uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, dto.MiembroResponse{
|
||||||
|
ID: miembro.Usuario.ID,
|
||||||
|
Email: miembro.Usuario.Email,
|
||||||
|
Name: miembro.Usuario.Name,
|
||||||
|
Activo: miembro.Usuario.Activo,
|
||||||
|
DebeCambiarPassword: miembro.Usuario.DebeCambiarPassword,
|
||||||
|
Rol: string(miembro.Rol),
|
||||||
|
MembresiaActiva: miembro.Activo,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func CrearMiembro(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
Email string `json:"email" binding:"required,email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
GrupoID uint `json:"grupo_id"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
rol, err := rolSolicitado(c, callerRol, req.Rol)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.GrupoID > 0 {
|
||||||
|
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorID(req.GrupoID)
|
||||||
|
if err != nil || grupo.EmpresaID != empresaID {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Grupo inválido para la empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
|
passwordTemporal := ""
|
||||||
|
creado := false
|
||||||
|
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
password := req.Password
|
||||||
|
if password == "" {
|
||||||
|
password, err = services.GenerarPasswordTemporal()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "No se pudo generar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
passwordTemporal = password
|
||||||
|
}
|
||||||
|
if len(password) < 8 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La contraseña debe tener al menos 8 caracteres"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
usuario = &models_seguridad.Usuario{
|
||||||
|
Email: email,
|
||||||
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Password: string(hash),
|
||||||
|
Activo: true,
|
||||||
|
DebeCambiarPassword: true,
|
||||||
|
}
|
||||||
|
if err := repo.Usuario.Crear(usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
creado = true
|
||||||
|
} else if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
if _, err := repo.Empresa.Membresia(empresaID, usuario.ID); err == nil {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "El usuario ya pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.AgregarMiembro(empresaID, usuario.ID, rol, req.GrupoID); err != nil {
|
||||||
|
if creado {
|
||||||
|
_ = repo.Usuario.Eliminar(usuario.ID)
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, gin.H{
|
||||||
|
"usuario": dto.MiembroResponse{
|
||||||
|
ID: usuario.ID,
|
||||||
|
Email: usuario.Email,
|
||||||
|
Name: usuario.Name,
|
||||||
|
Activo: usuario.Activo,
|
||||||
|
DebeCambiarPassword: usuario.DebeCambiarPassword,
|
||||||
|
Rol: string(rol),
|
||||||
|
MembresiaActiva: true,
|
||||||
|
CreatedAt: usuario.CreatedAt,
|
||||||
|
UpdatedAt: usuario.UpdatedAt,
|
||||||
|
},
|
||||||
|
"password_temporal": passwordTemporal,
|
||||||
|
"usuario_existente": !creado,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ActualizarMiembro(c *gin.Context) {
|
||||||
|
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
GrupoID uint `json:"grupo_id"`
|
||||||
|
Activo *bool `json:"activo"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
|
||||||
|
miembro, err := repo.Empresa.Membresia(empresaID, uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := puedeModificarMiembro(c, callerRol, miembro.Rol); err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorID(uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Name != "" {
|
||||||
|
usuario.Name = strings.TrimSpace(req.Name)
|
||||||
|
}
|
||||||
|
if req.Email != "" {
|
||||||
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
if email != usuario.Email {
|
||||||
|
if existente, err := repo.Usuario.ObtenerPorEmail(email); err == nil && existente.ID != usuario.ID {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "El email ya está registrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
usuario.Email = email
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := repo.Usuario.Guardar(usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Rol != "" {
|
||||||
|
nuevoRol, err := rolSolicitado(c, callerRol, req.Rol)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if miembro.Rol == models_seguridad.RolOwner && nuevoRol != models_seguridad.RolOwner {
|
||||||
|
if err := validarUltimoOwner(empresaID); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := repo.Empresa.ActualizarRolMiembro(empresaID, usuario.ID, nuevoRol); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
miembro.Rol = nuevoRol
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Activo != nil {
|
||||||
|
if !*req.Activo && miembro.Rol == models_seguridad.RolOwner {
|
||||||
|
if err := validarUltimoOwner(empresaID); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if *req.Activo {
|
||||||
|
if err := repo.Empresa.AgregarMiembro(empresaID, usuario.ID, miembro.Rol, 0); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := repo.Empresa.DesactivarMiembro(empresaID, usuario.ID); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, dto.MiembroResponse{
|
||||||
|
ID: usuario.ID,
|
||||||
|
Email: usuario.Email,
|
||||||
|
Name: usuario.Name,
|
||||||
|
Activo: usuario.Activo,
|
||||||
|
DebeCambiarPassword: usuario.DebeCambiarPassword,
|
||||||
|
Rol: string(miembro.Rol),
|
||||||
|
MembresiaActiva: miembro.Activo,
|
||||||
|
CreatedAt: usuario.CreatedAt,
|
||||||
|
UpdatedAt: usuario.UpdatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func EliminarMiembro(c *gin.Context) {
|
||||||
|
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
|
||||||
|
miembro, err := repo.Empresa.Membresia(empresaID, uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := puedeModificarMiembro(c, callerRol, miembro.Rol); err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if miembro.Rol == models_seguridad.RolOwner {
|
||||||
|
if err := validarUltimoOwner(empresaID); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.EliminarMiembro(empresaID, uint(usuarioID)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "El usuario fue removido de la empresa"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ActualizarEmpresa(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit string `json:"cuit"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
empresa, err := repo.Empresa.ObtenerPorID(utils.EmpresaID(c))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Empresa no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
input := models_seguridad.Empresa{Nombre: strings.TrimSpace(req.Nombre), Slug: strings.TrimSpace(req.Slug)}
|
||||||
|
if req.Cuit != "" {
|
||||||
|
cuit := strings.TrimSpace(req.Cuit)
|
||||||
|
input.Cuit = &cuit
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.Actualizar(empresa, input); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, empresa)
|
||||||
|
}
|
||||||
|
|
||||||
|
func rolSolicitado(c *gin.Context, callerRol models_seguridad.RolEmpresa, solicitado string) (models_seguridad.RolEmpresa, error) {
|
||||||
|
rol := models_seguridad.RolEmpresa(strings.ToUpper(strings.TrimSpace(solicitado)))
|
||||||
|
if rol == "" {
|
||||||
|
rol = models_seguridad.RolMiembro
|
||||||
|
}
|
||||||
|
if !rol.Valido() {
|
||||||
|
return "", errors.New("rol inválido")
|
||||||
|
}
|
||||||
|
|
||||||
|
if rol == models_seguridad.RolOwner && callerRol != models_seguridad.RolOwner && !utils.EsPlataformaAdmin(c) {
|
||||||
|
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 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if targetRol == models_seguridad.RolOwner {
|
||||||
|
return errors.New("solo el owner puede administrar a otro owner")
|
||||||
|
}
|
||||||
|
if callerRol == models_seguridad.RolAdmin && targetRol == models_seguridad.RolAdmin {
|
||||||
|
return errors.New("un administrador no puede modificar a otro administrador")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validarUltimoOwner(empresaID uint) error {
|
||||||
|
owners, err := r.ObtenerRepositorios().Empresa.ContarOwners(empresaID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if owners <= 1 {
|
||||||
|
return errors.New("la empresa debe conservar al menos un owner activo")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -15,7 +15,7 @@ func ActualizarGrupo(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
grupo, err := r.ObtenerRepositorios().Grupo.ObtenerPorID(uint(id))
|
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||||
return
|
return
|
||||||
@@ -25,6 +25,6 @@ func ActualizarGrupo(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r.ObtenerRepositorios().Grupo.Actualizar(grupo, input)
|
r.ObtenerRepositorios(c).Grupo.Actualizar(grupo, input)
|
||||||
c.JSON(http.StatusOK, grupo)
|
c.JSON(http.StatusOK, grupo)
|
||||||
}
|
}
|
||||||
@@ -18,7 +18,7 @@ func AgregarGrupoAUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Usuario.AgregarGrupoAUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
if err := r.ObtenerRepositorios(c).Usuario.AgregarGrupoAUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "no se pudo añadir el grupo al usuario"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "no se pudo añadir el grupo al usuario"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func AgregarPermisoAGrupo(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Grupo.AgregarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
if err := r.ObtenerRepositorios(c).Grupo.AgregarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func AgregarSubGrupo(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Grupo.AgregarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
if err := r.ObtenerRepositorios(c).Grupo.AgregarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ func CrearGrupo(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := r.ObtenerRepositorios().Grupo.Crear(&grupo); err != nil {
|
if err := r.ObtenerRepositorios(c).Grupo.Crear(&grupo); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ func EliminarGrupo(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := r.ObtenerRepositorios().Grupo.Eliminar(uint(id)); err != nil {
|
if err := r.ObtenerRepositorios(c).Grupo.Eliminar(uint(id)); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ func ObtenerGrupo(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
grupo, err := r.ObtenerRepositorios().Grupo.ObtenerPorIDConRelaciones(uint(id), true)
|
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorIDConRelaciones(uint(id), true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func ObtenerGrupos(c *gin.Context) {
|
func ObtenerGrupos(c *gin.Context) {
|
||||||
grupos, err := r.ObtenerRepositorios().Grupo.ObtenerTodosConRelaciones()
|
grupos, err := r.ObtenerRepositorios(c).Grupo.ObtenerTodosConRelaciones()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ func ObtenerGruposDeUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
grupos, err := r.ObtenerRepositorios().Usuario.ObtenerGruposPorUsuarioID(uint(usuarioID))
|
grupos, err := r.ObtenerRepositorios(c).Usuario.ObtenerGruposPorUsuarioID(uint(usuarioID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se ha podido obtener los grupos del usuario"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se ha podido obtener los grupos del usuario"})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
usuario, err := r.ObtenerRepositorios().Usuario.ObtenerPorEmailConGrupos(request.Email)
|
usuario, err := r.ObtenerRepositorios(c).Usuario.ObtenerPorEmailConGrupos(request.Email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
@@ -40,10 +40,9 @@ func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
grupos := make([]dto.GrupoSimpleDTO, 0, len(usuario.Grupos))
|
grupos := make([]dto.GrupoSimpleDTO, 0, len(usuario.Grupos))
|
||||||
for i := range usuario.Grupos {
|
for i := range usuario.Grupos {
|
||||||
grupoCompleto, err := r.ObtenerRepositorios().Grupo.ObtenerPorIDConRelaciones(usuario.Grupos[i].ID, true)
|
grupoCompleto, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorIDConRelaciones(usuario.Grupos[i].ID, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ func QuitarGrupoAUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Usuario.QuitarGrupoDeUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
if err := r.ObtenerRepositorios(c).Usuario.QuitarGrupoDeUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "no se pudo quitar el grupo al usuario"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "no se pudo quitar el grupo al usuario"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func QuitarPermisoAGrupo(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Grupo.QuitarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
if err := r.ObtenerRepositorios(c).Grupo.QuitarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func QuitarSubGrupo(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Grupo.QuitarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
if err := r.ObtenerRepositorios(c).Grupo.QuitarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,14 +25,14 @@ func BusquedaLogs(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
var logs []logs.Log
|
var logs []logs.Log
|
||||||
|
|
||||||
if logs, err = r.ObtenerRepositorios().Logs.ObtenerConFiltros(int(pag), filtros); err != nil {
|
if logs, err = r.ObtenerRepositorios(c).Logs.ObtenerConFiltros(int(pag), filtros); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
logsdto := dto_builders.NewLogTablaBuilder().ConLogs(logs).Build()
|
logsdto := dto_builders.NewLogTablaBuilder().ConLogs(logs).Build()
|
||||||
|
|
||||||
cantpags, err := r.ObtenerRepositorios().Logs.CantPaginasConFiltros(filtros)
|
cantpags, err := r.ObtenerRepositorios(c).Logs.CantPaginasConFiltros(filtros)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ func ObtenerLog(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
logs, err := r.ObtenerRepositorios().Logs.ObtenerPorPaginas(uint(pag))
|
logs, err := r.ObtenerRepositorios(c).Logs.ObtenerPorPaginas(uint(pag))
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ func ObtenerLogs(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
repo := r.ObtenerRepositorios().Logs
|
repo := r.ObtenerRepositorios(c).Logs
|
||||||
|
|
||||||
logs, err := repo.ObtenerPorPaginas(uint(pag))
|
logs, err := repo.ObtenerPorPaginas(uint(pag))
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func ActualizarMarca(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtener la marca actual
|
// Obtener la marca actual
|
||||||
marca, err := r.ObtenerRepositorios().Marca.ObtenerPorID(uint(id))
|
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Marca no encontrada"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Marca no encontrada"})
|
||||||
return
|
return
|
||||||
@@ -41,13 +41,13 @@ func ActualizarMarca(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verificar que no exista otra marca con el mismo nombre
|
// Verificar que no exista otra marca con el mismo nombre
|
||||||
if existing, _ := r.ObtenerRepositorios().Marca.ObtenerPorNombre(input.Nombre); existing != nil && existing.ID != marca.ID {
|
if existing, _ := r.ObtenerRepositorios(c).Marca.ObtenerPorNombre(input.Nombre); existing != nil && existing.ID != marca.ID {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ya existe una marca con ese nombre"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ya existe una marca con ese nombre"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
uid := c.GetUint("userID")
|
uid := c.GetUint("userID")
|
||||||
if err := r.ObtenerRepositorios().Marca.Actualizar(marca, input, uid); err != nil {
|
if err := r.ObtenerRepositorios(c).Marca.Actualizar(marca, input, uid); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ func AltaMarca(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uid := c.GetUint("userID")
|
uid := c.GetUint("userID")
|
||||||
marca, err := r.ObtenerRepositorios().Marca.ObtenerPorID(uint(id))
|
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Marca no encontrada"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Marca no encontrada"})
|
||||||
return
|
return
|
||||||
@@ -33,7 +33,7 @@ func AltaMarca(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
marca.DeletedAt = gorm.DeletedAt{}
|
marca.DeletedAt = gorm.DeletedAt{}
|
||||||
if err := r.ObtenerRepositorios().Marca.Alta(marca, *marca, uid); err != nil {
|
if err := r.ObtenerRepositorios(c).Marca.Alta(marca, *marca, uid); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ func CrearMarca(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := r.ObtenerRepositorios().Marca.ObtenerPorNombre(marca.Nombre)
|
_, err := r.ObtenerRepositorios(c).Marca.ObtenerPorNombre(marca.Nombre)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ya existe una marca con ese nombre"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ya existe una marca con ese nombre"})
|
||||||
return
|
return
|
||||||
@@ -23,7 +23,7 @@ func CrearMarca(c *gin.Context) {
|
|||||||
|
|
||||||
uid := c.GetUint("userID")
|
uid := c.GetUint("userID")
|
||||||
|
|
||||||
err = r.ObtenerRepositorios().Marca.Crear(marca, uid)
|
err = r.ObtenerRepositorios(c).Marca.Crear(marca, uid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ func EliminarMarca(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uid := c.GetUint("userID")
|
uid := c.GetUint("userID")
|
||||||
err = r.ObtenerRepositorios().Marca.Baja(uint(id), uid)
|
err = r.ObtenerRepositorios(c).Marca.Baja(uint(id), uid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func ObtenerMarcas(c *gin.Context) {
|
func ObtenerMarcas(c *gin.Context) {
|
||||||
marcas, err := r.ObtenerRepositorios().Marca.ObtenerTodos()
|
marcas, err := r.ObtenerRepositorios(c).Marca.ObtenerTodos()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ func ActualizarPermiso(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
permiso, err := r.ObtenerRepositorios().Permiso.ObtenerPorID(uint(id))
|
permiso, err := r.ObtenerRepositorios(c).Permiso.ObtenerPorID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Permiso no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Permiso no encontrado"})
|
||||||
return
|
return
|
||||||
@@ -25,6 +25,6 @@ func ActualizarPermiso(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r.ObtenerRepositorios().Permiso.Actualizar(permiso, input)
|
r.ObtenerRepositorios(c).Permiso.Actualizar(permiso, input)
|
||||||
c.JSON(http.StatusOK, permiso)
|
c.JSON(http.StatusOK, permiso)
|
||||||
}
|
}
|
||||||
@@ -14,7 +14,7 @@ func CrearPermiso(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := r.ObtenerRepositorios().Permiso.Crear(&permiso); err != nil {
|
if err := r.ObtenerRepositorios(c).Permiso.Crear(&permiso); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ func EliminarPermiso(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := r.ObtenerRepositorios().Permiso.Eliminar(uint(id)); err != nil {
|
if err := r.ObtenerRepositorios(c).Permiso.Eliminar(uint(id)); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func ObtenerPermisos(c *gin.Context) {
|
func ObtenerPermisos(c *gin.Context) {
|
||||||
permisos, err := r.ObtenerRepositorios().Permiso.ObtenerTodos()
|
permisos, err := r.ObtenerRepositorios(c).Permiso.ObtenerTodos()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ func ObtenerPermisosUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
usuario, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(uint(userID))
|
usuario, err := r.ObtenerRepositorios(c).Usuario.PrecargarGruposPermisosPorID(uint(userID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
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,204 @@
|
|||||||
|
package plataforma
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EmpresaAdminResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit *string `json:"cuit,omitempty"`
|
||||||
|
Activa bool `json:"activa"`
|
||||||
|
Miembros int64 `json:"miembros"`
|
||||||
|
Owners int64 `json:"owners"`
|
||||||
|
CreatedAt any `json:"created_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListarEmpresas(c *gin.Context) {
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
empresas, err := repo.Empresa.ListarTodas()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta := make([]EmpresaAdminResponse, 0, len(empresas))
|
||||||
|
for _, empresa := range empresas {
|
||||||
|
miembros, _ := repo.Empresa.ContarMiembros(empresa.ID)
|
||||||
|
owners, _ := repo.Empresa.ContarOwners(empresa.ID)
|
||||||
|
respuesta = append(respuesta, EmpresaAdminResponse{
|
||||||
|
ID: empresa.ID,
|
||||||
|
Nombre: empresa.Nombre,
|
||||||
|
Slug: empresa.Slug,
|
||||||
|
Cuit: empresa.Cuit,
|
||||||
|
Activa: empresa.Activa,
|
||||||
|
Miembros: miembros,
|
||||||
|
Owners: owners,
|
||||||
|
CreatedAt: empresa.CreatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"empresas": respuesta, "total": len(respuesta)})
|
||||||
|
}
|
||||||
|
|
||||||
|
func CrearEmpresa(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Nombre string `json:"nombre" binding:"required"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit string `json:"cuit"`
|
||||||
|
OwnerEmail string `json:"owner_email" binding:"required,email"`
|
||||||
|
OwnerName string `json:"owner_name"`
|
||||||
|
OwnerPassword string `json:"owner_password"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
email := strings.ToLower(strings.TrimSpace(req.OwnerEmail))
|
||||||
|
owner, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
|
passwordTemporal := ""
|
||||||
|
creado := false
|
||||||
|
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
password := req.OwnerPassword
|
||||||
|
if password == "" {
|
||||||
|
password, err = services.GenerarPasswordTemporal()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "No se pudo generar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
passwordTemporal = password
|
||||||
|
}
|
||||||
|
if len(password) < 8 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La contraseña del owner debe tener al menos 8 caracteres"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
nombre := strings.TrimSpace(req.OwnerName)
|
||||||
|
if nombre == "" {
|
||||||
|
nombre = strings.Split(email, "@")[0]
|
||||||
|
}
|
||||||
|
owner = &models_seguridad.Usuario{
|
||||||
|
Email: email,
|
||||||
|
Name: nombre,
|
||||||
|
Password: string(hash),
|
||||||
|
Activo: true,
|
||||||
|
DebeCambiarPassword: true,
|
||||||
|
}
|
||||||
|
if err := repo.Usuario.Crear(owner); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
creado = true
|
||||||
|
} else if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresa := models_seguridad.Empresa{
|
||||||
|
Nombre: strings.TrimSpace(req.Nombre),
|
||||||
|
Slug: strings.TrimSpace(req.Slug),
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Cuit) != "" {
|
||||||
|
cuit := strings.TrimSpace(req.Cuit)
|
||||||
|
empresa.Cuit = &cuit
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.Crear(&empresa, owner.ID); err != nil {
|
||||||
|
if creado {
|
||||||
|
_ = repo.Usuario.Eliminar(owner.ID)
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, gin.H{
|
||||||
|
"empresa": empresa,
|
||||||
|
"owner": owner,
|
||||||
|
"password_temporal": passwordTemporal,
|
||||||
|
"owner_existente": !creado,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ActualizarEmpresa(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
|
||||||
|
}
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit *string `json:"cuit"`
|
||||||
|
Activa *bool `json:"activa"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
empresa, err := repo.Empresa.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Empresa no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(req.Nombre) != "" {
|
||||||
|
empresa.Nombre = strings.TrimSpace(req.Nombre)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Slug) != "" {
|
||||||
|
empresa.Slug = strings.TrimSpace(req.Slug)
|
||||||
|
}
|
||||||
|
if req.Cuit != nil {
|
||||||
|
cuit := strings.TrimSpace(*req.Cuit)
|
||||||
|
if cuit == "" {
|
||||||
|
empresa.Cuit = nil
|
||||||
|
} else {
|
||||||
|
empresa.Cuit = &cuit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if req.Activa != nil {
|
||||||
|
empresa.Activa = *req.Activa
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.Guardar(empresa); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, empresa)
|
||||||
|
}
|
||||||
|
|
||||||
|
func DesactivarEmpresa(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
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios().Empresa.Desactivar(uint(id)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Empresa desactivada"})
|
||||||
|
}
|
||||||
@@ -10,13 +10,13 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ActualizarRepuesto(c *gin.Context){
|
func ActualizarRepuesto(c *gin.Context) {
|
||||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (id<1){
|
if id < 1 {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ func ActualizarRepuesto(c *gin.Context){
|
|||||||
|
|
||||||
data.ID = &id
|
data.ID = &id
|
||||||
|
|
||||||
marca, err := r.ObtenerRepositorios().Marca.ObtenerPorID(data.Marca)
|
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(data.Marca)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
@@ -40,14 +40,14 @@ func ActualizarRepuesto(c *gin.Context){
|
|||||||
ConMarca(marca.ID).
|
ConMarca(marca.ID).
|
||||||
Build()
|
Build()
|
||||||
|
|
||||||
entity, err := r.ObtenerRepositorios().Repuesto.ObtenerPorID(uint(id))
|
entity, err := r.ObtenerRepositorios(c).Repuesto.ObtenerPorID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, _ := c.Get("userID")
|
uid, _ := c.Get("userID")
|
||||||
if err := r.ObtenerRepositorios().Repuesto.Actualizar(entity, &repuesto, uid.(uint)); err != nil {
|
if err := r.ObtenerRepositorios(c).Repuesto.Actualizar(entity, &repuesto, uid.(uint)); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ func AltaRepuestos(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uid := c.MustGet("userID").(uint)
|
uid := c.MustGet("userID").(uint)
|
||||||
if _, err := r.ObtenerRepositorios().Repuesto.AltaRepuesto(uint(id), uint(uid)); err != nil {
|
if _, err := r.ObtenerRepositorios(c).Repuesto.AltaRepuesto(uint(id), uint(uid)); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,13 +17,13 @@ func CrearRepuesto(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
marca, err := r.ObtenerRepositorios().Marca.ObtenerPorID(data.Marca)
|
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(data.Marca)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Marca.CrearFaltante(*marca); err != nil {
|
if err := r.ObtenerRepositorios(c).Marca.CrearFaltante(*marca); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,7 @@ func CrearRepuesto(c *gin.Context) {
|
|||||||
Build()
|
Build()
|
||||||
|
|
||||||
uid, _ := c.Get("userID")
|
uid, _ := c.Get("userID")
|
||||||
if err := r.ObtenerRepositorios().Repuesto.Crear(&repuesto, uid.(uint)); err != nil {
|
if err := r.ObtenerRepositorios(c).Repuesto.Crear(&repuesto, uid.(uint)); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ func EliminarRepuesto(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uid, _ := c.Get("userID")
|
uid, _ := c.Get("userID")
|
||||||
if err := r.ObtenerRepositorios().Repuesto.Baja(uint(id), uid.(uint)); err != nil {
|
if err := r.ObtenerRepositorios(c).Repuesto.Baja(uint(id), uid.(uint)); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,14 +9,14 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ObtenerRepuesto(c *gin.Context){
|
func ObtenerRepuesto(c *gin.Context) {
|
||||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
repuesto, err := r.ObtenerRepositorios().Repuesto.ObtenerPorID(uint(id))
|
repuesto, err := r.ObtenerRepositorios(c).Repuesto.ObtenerPorID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func ObtenerRepuestos(c *gin.Context) {
|
func ObtenerRepuestos(c *gin.Context) {
|
||||||
repuestos, err := r.ObtenerRepositorios().Repuesto.ObtenerTodosConMarca()
|
repuestos, err := r.ObtenerRepositorios(c).Repuesto.ObtenerTodosConMarca()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func ActualizarUsuario(c *gin.Context) {
|
|||||||
|
|
||||||
idconv, _ := strconv.ParseUint(id, 10, 64)
|
idconv, _ := strconv.ParseUint(id, 10, 64)
|
||||||
|
|
||||||
usuario, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(uint(idconv))
|
usuario, err := r.ObtenerRepositorios(c).Usuario.ObtenerPorID(uint(idconv))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
return
|
return
|
||||||
@@ -39,7 +39,7 @@ func ActualizarUsuario(c *gin.Context) {
|
|||||||
usuario.Email = usuarioReq.Email
|
usuario.Email = usuarioReq.Email
|
||||||
usuario.Name = usuarioReq.Name
|
usuario.Name = usuarioReq.Name
|
||||||
|
|
||||||
r.ObtenerRepositorios().Usuario.Guardar(usuario)
|
r.ObtenerRepositorios(c).Usuario.Guardar(usuario)
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, usuario)
|
c.JSON(http.StatusCreated, usuario)
|
||||||
}
|
}
|
||||||
@@ -15,7 +15,7 @@ func CrearUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Usuario.Crear(&usuario); err != nil {
|
if err := r.ObtenerRepositorios(c).Usuario.Crear(&usuario); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ func EliminarUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.ObtenerRepositorios().Usuario.Eliminar(uint(id)); err != nil {
|
if err := r.ObtenerRepositorios(c).Usuario.Eliminar(uint(id)); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ func ObtenerUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
usuario, err := r.ObtenerRepositorios().Usuario.BuscarPorID(uint(id))
|
usuario, err := r.ObtenerRepositorios(c).Usuario.BuscarPorID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ func ObtenerUsuarios(c *gin.Context) {
|
|||||||
tamaño = 10
|
tamaño = 10
|
||||||
}
|
}
|
||||||
|
|
||||||
usuarios, total, err := r.ObtenerRepositorios().Usuario.ObtenerTodosPaginado(int(pagina), int(tamaño))
|
usuarios, total, err := r.ObtenerRepositorios(c).Usuario.ObtenerTodosPaginado(int(pagina), int(tamaño))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -14,11 +14,10 @@ func NewLogTablaBuilder() *LogTablaBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (b *LogTablaBuilder) ConLogs(logs []logs.Log) *LogTablaBuilder {
|
func (b *LogTablaBuilder) ConLogs(logs []logs.Log) *LogTablaBuilder {
|
||||||
b.logs =logs;
|
b.logs = logs
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func (b *LogTablaBuilder) Build() []dto.LogTablaDto {
|
func (b *LogTablaBuilder) Build() []dto.LogTablaDto {
|
||||||
var dtos []dto.LogTablaDto
|
var dtos []dto.LogTablaDto
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,38 @@
|
|||||||
package dto
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type EmpresaResumen struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Activa bool `json:"activa"`
|
||||||
|
Rol string `json:"rol,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UsuarioResumen struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Activo bool `json:"activo"`
|
||||||
|
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuthResponse struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
Permissions []uint `json:"permissions"`
|
||||||
|
Empresa *EmpresaResumen `json:"empresa,omitempty"`
|
||||||
|
Empresas []EmpresaResumen `json:"empresas"`
|
||||||
|
EmpresaRol string `json:"empresa_rol"`
|
||||||
|
EsPlataformaAdmin bool `json:"es_plataforma_admin"`
|
||||||
|
Usuario UsuarioResumen `json:"usuario"`
|
||||||
|
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TokenResponse se mantiene por compatibilidad con clientes anteriores.
|
||||||
type TokenResponse struct {
|
type TokenResponse struct {
|
||||||
AccessToken string `json:"access_token"`
|
AccessToken string `json:"access_token"`
|
||||||
RefreshToken string `json:"refresh_token"`
|
RefreshToken string `json:"refresh_token"`
|
||||||
@@ -19,4 +52,34 @@ type MeResponse struct {
|
|||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Permissions []uint `json:"permissions"`
|
Permissions []uint `json:"permissions"`
|
||||||
|
Empresa *EmpresaResumen `json:"empresa,omitempty"`
|
||||||
|
Empresas []EmpresaResumen `json:"empresas"`
|
||||||
|
EmpresaRol string `json:"empresa_rol"`
|
||||||
|
EsPlataformaAdmin bool `json:"es_plataforma_admin"`
|
||||||
|
Activo bool `json:"activo"`
|
||||||
|
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type InvitacionInfo struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Empresa string `json:"empresa"`
|
||||||
|
EmpresaID uint `json:"empresa_id"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
ExpiraEn time.Time `json:"expira_en"`
|
||||||
|
Valida bool `json:"valida"`
|
||||||
|
Usada bool `json:"usada"`
|
||||||
|
Expirada bool `json:"expirada"`
|
||||||
|
UsuarioExistente bool `json:"usuario_existente"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type MiembroResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Activo bool `json:"activo"`
|
||||||
|
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
MembresiaActiva bool `json:"membresia_activa"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
+32
-2
@@ -11,6 +11,9 @@ import (
|
|||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// MapClaims es un alias para no filtrar el paquete jwt a los consumidores.
|
||||||
|
type MapClaims = jwt.MapClaims
|
||||||
|
|
||||||
const (
|
const (
|
||||||
TokenTypeAccess = "access"
|
TokenTypeAccess = "access"
|
||||||
TokenTypeRefresh = "refresh"
|
TokenTypeRefresh = "refresh"
|
||||||
@@ -18,6 +21,9 @@ const (
|
|||||||
ClaimPermissions = "permissions"
|
ClaimPermissions = "permissions"
|
||||||
ClaimType = "typ"
|
ClaimType = "typ"
|
||||||
ClaimSubject = "sub"
|
ClaimSubject = "sub"
|
||||||
|
ClaimEmpresaID = "empresa_id"
|
||||||
|
ClaimEmpresaRol = "empresa_rol"
|
||||||
|
ClaimPlataformaAdmin = "es_plataforma_admin"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -50,8 +56,9 @@ func GetSecret() ([]byte, error) {
|
|||||||
return jwtSecret, nil
|
return jwtSecret, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GenerarToken firma un token HS256 con los datos del usuario y sus permisos planos.
|
// GenerarToken firma un token HS256 con los datos del usuario, su empresa
|
||||||
func GenerarToken(userID uint, email, name, tokenType string, permissions []uint, duration time.Duration) (string, error) {
|
// activa y sus permisos planos.
|
||||||
|
func GenerarToken(userID uint, empresaID uint, empresaRol string, esPlataformaAdmin bool, email, name, tokenType string, permissions []uint, duration time.Duration) (string, error) {
|
||||||
secret, err := GetSecret()
|
secret, err := GetSecret()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -61,6 +68,9 @@ func GenerarToken(userID uint, email, name, tokenType string, permissions []uint
|
|||||||
ClaimSubject: userID,
|
ClaimSubject: userID,
|
||||||
"email": email,
|
"email": email,
|
||||||
"name": name,
|
"name": name,
|
||||||
|
ClaimEmpresaID: empresaID,
|
||||||
|
ClaimEmpresaRol: empresaRol,
|
||||||
|
ClaimPlataformaAdmin: esPlataformaAdmin,
|
||||||
ClaimPermissions: permissions,
|
ClaimPermissions: permissions,
|
||||||
ClaimType: tokenType,
|
ClaimType: tokenType,
|
||||||
"exp": time.Now().Add(duration).Unix(),
|
"exp": time.Now().Add(duration).Unix(),
|
||||||
@@ -147,6 +157,26 @@ func ClaimUint(claims jwt.MapClaims, key string) (uint, bool) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ClaimBool interpreta un claim booleano.
|
||||||
|
func ClaimBool(claims jwt.MapClaims, key string) bool {
|
||||||
|
value, ok := claims[key]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
v, _ := value.(bool)
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClaimString interpreta un claim string.
|
||||||
|
func ClaimString(claims jwt.MapClaims, key string) string {
|
||||||
|
value, ok := claims[key]
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
v, _ := value.(string)
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
// PermisosDesdeClaims extrae la lista plana de IDs de permisos del token.
|
// PermisosDesdeClaims extrae la lista plana de IDs de permisos del token.
|
||||||
func PermisosDesdeClaims(claims jwt.MapClaims) []uint {
|
func PermisosDesdeClaims(claims jwt.MapClaims) []uint {
|
||||||
raw, ok := claims[ClaimPermissions]
|
raw, ok := claims[ClaimPermissions]
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ func TestTokenRoundTrip(t *testing.T) {
|
|||||||
os.Setenv("JWTString", "test-secret")
|
os.Setenv("JWTString", "test-secret")
|
||||||
t.Cleanup(func() { os.Unsetenv("JWTString") })
|
t.Cleanup(func() { os.Unsetenv("JWTString") })
|
||||||
|
|
||||||
token, err := GenerarToken(7, "a@b.c", "Nombre", TokenTypeAccess, []uint{1, 2, 4}, time.Minute)
|
token, err := GenerarToken(7, 3, "OWNER", false, "a@b.c", "Nombre", TokenTypeAccess, []uint{1, 2, 4}, time.Minute)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("generar token: %v", err)
|
t.Fatalf("generar token: %v", err)
|
||||||
}
|
}
|
||||||
@@ -25,6 +25,14 @@ func TestTokenRoundTrip(t *testing.T) {
|
|||||||
t.Fatalf("sub esperado 7, obtenido %v (%v)", id, ok)
|
t.Fatalf("sub esperado 7, obtenido %v (%v)", id, ok)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if empresa, ok := ClaimUint(claims, ClaimEmpresaID); !ok || empresa != 3 {
|
||||||
|
t.Fatalf("empresa esperada 3, obtenida %v (%v)", empresa, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
if rol := ClaimString(claims, ClaimEmpresaRol); rol != "OWNER" {
|
||||||
|
t.Fatalf("rol esperado OWNER, obtenido %q", rol)
|
||||||
|
}
|
||||||
|
|
||||||
if got := PermisosDesdeClaims(claims); !reflect.DeepEqual(got, []uint{1, 2, 4}) {
|
if got := PermisosDesdeClaims(claims); !reflect.DeepEqual(got, []uint{1, 2, 4}) {
|
||||||
t.Fatalf("permisos esperados [1 2 4], obtenidos %v", got)
|
t.Fatalf("permisos esperados [1 2 4], obtenidos %v", got)
|
||||||
}
|
}
|
||||||
|
|||||||
+165
-22
@@ -4,47 +4,169 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"repuestera_back/config"
|
||||||
"repuestera_back/jwtutils"
|
"repuestera_back/jwtutils"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/utils"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AuthMiddleware valida la firma del JWT y, opcionalmente, exige que el usuario
|
// AuthMiddleware valida la firma del JWT, exige una empresa activa en el token
|
||||||
// tenga al menos uno de los permisos indicados. Los permisos viajan en el claim
|
// y valida la membresía del usuario. Opcionalmente exige alguno de los
|
||||||
// "permissions" como una lista plana de IDs.
|
// permisos indicados.
|
||||||
func AuthMiddleware(permisosRequeridos ...uint) gin.HandlerFunc {
|
func AuthMiddleware(permisosRequeridos ...uint) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
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 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")
|
authHeader := c.GetHeader("Authorization")
|
||||||
if authHeader == "" {
|
if authHeader == "" {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: Header Authorization no presente"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: Header Authorization no presente"})
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return nil, 0, false
|
||||||
}
|
}
|
||||||
|
|
||||||
partes := strings.Split(authHeader, " ")
|
partes := strings.Split(authHeader, " ")
|
||||||
if len(partes) != 2 || partes[0] != "Bearer" {
|
if len(partes) != 2 || !strings.EqualFold(partes[0], "Bearer") {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Formato de token invalido"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Formato de token inválido"})
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return nil, 0, false
|
||||||
}
|
}
|
||||||
|
|
||||||
claims, err := jwtutils.ValidarTokenDeTipo(partes[1], jwtutils.TokenTypeAccess)
|
claims, err := jwtutils.ValidarTokenDeTipo(partes[1], jwtutils.TokenTypeAccess)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token invalido o expirado"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido o expirado"})
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return nil, 0, false
|
||||||
}
|
}
|
||||||
|
|
||||||
userID, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
userID, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||||
if !ok {
|
if !ok || userID == 0 {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token invalido: usuario no encontrado"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido: usuario no encontrado"})
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return nil, 0, false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return claims, userID, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func cargarContexto(c *gin.Context, claims jwtutils.MapClaims, userID, empresaID uint) {
|
||||||
permisos := jwtutils.PermisosDesdeClaims(claims)
|
permisos := jwtutils.PermisosDesdeClaims(claims)
|
||||||
c.Set("userID", userID)
|
c.Set("userID", userID)
|
||||||
|
c.Set(utils.ContextEmpresaIDKey, empresaID)
|
||||||
|
c.Set(utils.ContextEmpresaRolKey, jwtutils.ClaimString(claims, jwtutils.ClaimEmpresaRol))
|
||||||
c.Set(utils.ContextPermissionsKey, permisos)
|
c.Set(utils.ContextPermissionsKey, permisos)
|
||||||
|
|
||||||
if email, ok := claims["email"].(string); ok {
|
if email, ok := claims["email"].(string); ok {
|
||||||
@@ -54,20 +176,44 @@ func AuthMiddleware(permisosRequeridos ...uint) gin.HandlerFunc {
|
|||||||
c.Set("name", name)
|
c.Set("name", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(permisosRequeridos) > 0 && !utils.UsuarioTieneAlgunPermiso(c, permisosRequeridos) {
|
// Un rol de plataforma revocado en la base no debe seguir vigente hasta
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para realizar esta accion"})
|
// que expire el token.
|
||||||
c.Abort()
|
plataforma := jwtutils.ClaimBool(claims, jwtutils.ClaimPlataformaAdmin) && esPlataformaAdmin(userID)
|
||||||
return
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Next()
|
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 {
|
func PermisoMiddleware(permisoID uint) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
if !utils.UsuarioTienePermiso(c, permisoID) {
|
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()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -78,13 +224,10 @@ func PermisoMiddleware(permisoID uint) gin.HandlerFunc {
|
|||||||
func PermisosMiddleware(permisosIDs ...uint) gin.HandlerFunc {
|
func PermisosMiddleware(permisosIDs ...uint) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
if !utils.UsuarioTieneAlgunPermiso(c, permisosIDs) {
|
if !utils.UsuarioTieneAlgunPermiso(c, permisosIDs) {
|
||||||
c.JSON(http.StatusForbidden, gin.H{
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para realizar esta acción"})
|
||||||
"error": "No tienes permiso para realizar esta accion",
|
|
||||||
})
|
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
type Almacen struct {
|
type Almacen struct {
|
||||||
ID string `gorm:"primaryKey;type:varchar(5)" json:"id"`
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_almacen_empresa_codigo,priority:1" json:"empresaId"`
|
||||||
|
Codigo string `gorm:"type:varchar(5);not null;uniqueIndex:uq_almacen_empresa_codigo,priority:2" json:"codigo"`
|
||||||
Ubicacion string `gorm:"type:varchar(40)" json:"ubicacion"`
|
Ubicacion string `gorm:"type:varchar(40)" json:"ubicacion"`
|
||||||
Stocks []Stock `gorm:"foreignKey:AlmacenID" json:"stocks,omitempty"`
|
Stocks []Stock `gorm:"foreignKey:AlmacenID" json:"stocks,omitempty"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,9 @@ import (
|
|||||||
|
|
||||||
type Cliente struct {
|
type Cliente struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_cliente_empresa_cuit,priority:1" json:"empresaId"`
|
||||||
Nombre string `gorm:"type:varchar(40)" json:"nombre"`
|
Nombre string `gorm:"type:varchar(40)" json:"nombre"`
|
||||||
Cuit string `gorm:"type:varchar(11);uniqueIndex;not null" json:"cuit"`
|
Cuit string `gorm:"type:varchar(11);not null;uniqueIndex:uq_cliente_empresa_cuit,priority:2" json:"cuit"`
|
||||||
Email sql.NullString `gorm:"type:varchar(80)" json:"email"`
|
Email sql.NullString `gorm:"type:varchar(80)" json:"email"`
|
||||||
Facturas []Factura `gorm:"foreignKey:ClienteID" json:"facturas,omitempty"`
|
Facturas []Factura `gorm:"foreignKey:ClienteID" json:"facturas,omitempty"`
|
||||||
Recibos []Recibo `gorm:"foreignKey:ClienteID" json:"recibos,omitempty"`
|
Recibos []Recibo `gorm:"foreignKey:ClienteID" json:"recibos,omitempty"`
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
import (
|
import (
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
"repuestera_back/models/seguridad"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
// este lo uso de base para los distintos tipos de comprobantes
|
// Comprobante es la base de los distintos tipos de comprobantes.
|
||||||
|
// EmpresaID se propaga automáticamente a todas las tablas que lo embeben.
|
||||||
type Comprobante struct {
|
type Comprobante struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
// Numero string `gorm:"size:50;not null" json:"numero"`
|
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
Estado string `gorm:"type:varchar(20);not null" json:"estado"`
|
Estado string `gorm:"type:varchar(20);not null" json:"estado"`
|
||||||
Total float64 `gorm:"type:decimal(15,2);not null" json:"total"`
|
Total float64 `gorm:"type:decimal(15,2);not null" json:"total"`
|
||||||
ResponsableID uint `gorm:"column:usuarioID"`
|
ResponsableID uint `gorm:"column:usuarioID"`
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import "gorm.io/gorm"
|
|||||||
|
|
||||||
type AsientoContable struct {
|
type AsientoContable struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
ComprobanteTipo string `gorm:"type:varchar(20);not null"`
|
ComprobanteTipo string `gorm:"type:varchar(20);not null"`
|
||||||
ComprobanteID uint
|
ComprobanteID uint
|
||||||
Movimientos []MovimientoContable `gorm:"foreignKey:AsientoID"`
|
Movimientos []MovimientoContable `gorm:"foreignKey:AsientoID"`
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import "gorm.io/gorm"
|
|||||||
|
|
||||||
type CuentaContable struct {
|
type CuentaContable struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
Nombre string `gorm:"type:varchar(30);not null"`
|
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_cuenta_empresa_nombre,priority:1" json:"empresaId"`
|
||||||
|
Nombre string `gorm:"type:varchar(30);not null;uniqueIndex:uq_cuenta_empresa_nombre,priority:2"`
|
||||||
Tipo string `gorm:"type:varchar(12);not null"`
|
Tipo string `gorm:"type:varchar(12);not null"`
|
||||||
Movimientos []MovimientoContable `gorm:"foreignKey:CuentaID"`
|
Movimientos []MovimientoContable `gorm:"foreignKey:CuentaID"`
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@ import "gorm.io/gorm"
|
|||||||
|
|
||||||
type MovimientoContable struct {
|
type MovimientoContable struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
AsientoID uint `gorm:"column:asientoID"`
|
AsientoID uint `gorm:"column:asientoID"`
|
||||||
Asiento AsientoContable `gorm:"foreignKey:AsientoID"`
|
Asiento AsientoContable `gorm:"foreignKey:AsientoID"`
|
||||||
CuentaID uint `gorm:"column:cuentaID"`
|
CuentaID uint `gorm:"column:cuentaID"`
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import "gorm.io/gorm"
|
|||||||
|
|
||||||
type Descuento struct {
|
type Descuento struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
|
|
||||||
Nombre string `gorm:"type:varchar(100);not null"`
|
Nombre string `gorm:"type:varchar(100);not null"`
|
||||||
Descripcion string `gorm:"type:text"`
|
Descripcion string `gorm:"type:text"`
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import "gorm.io/gorm"
|
|||||||
|
|
||||||
type FormaDePago struct {
|
type FormaDePago struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
Descripcion string `gorm:"type:varchar(20);not null" json:"desripcion" `
|
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_formapago_empresa_desc,priority:1" json:"empresaId"`
|
||||||
|
Descripcion string `gorm:"type:varchar(20);not null;uniqueIndex:uq_formapago_empresa_desc,priority:2" json:"descripcion"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (FormaDePago) TableName() string {
|
func (FormaDePago) TableName() string {
|
||||||
|
|||||||
@@ -10,10 +10,11 @@ import (
|
|||||||
|
|
||||||
type Log struct {
|
type Log struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index:idx_logs_empresa_created,priority:1" json:"empresaId"`
|
||||||
UsuarioID uint `gorm:"index;not null" json:"usuarioId"`
|
UsuarioID uint `gorm:"index;not null" json:"usuarioId"`
|
||||||
Accion string `gorm:"type:varchar(50);not null" json:"accion"`
|
Accion string `gorm:"type:varchar(50);not null" json:"accion"`
|
||||||
Detalles datatypes.JSONSlice[LogDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
Detalles datatypes.JSONSlice[LogDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `gorm:"index:idx_logs_empresa_created,priority:2" json:"created_at"`
|
||||||
Usuario models_seguridad.Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
Usuario models_seguridad.Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import (
|
|||||||
|
|
||||||
type Marca struct {
|
type Marca struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
Nombre string `gorm:"uniqueIndex;not null;type:varchar(70)" json:"nombre"`
|
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_marca_empresa_nombre,priority:1" json:"empresaId"`
|
||||||
|
Nombre string `gorm:"not null;type:varchar(70);uniqueIndex:uq_marca_empresa_nombre,priority:2" json:"nombre"`
|
||||||
Repuestos []Repuesto `gorm:"foreignKey:MarcaID" json:"repuestos"`
|
Repuestos []Repuesto `gorm:"foreignKey:MarcaID" json:"repuestos"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import "gorm.io/gorm"
|
|||||||
|
|
||||||
type Pago struct {
|
type Pago struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
FormaDePagoID uint `gorm:"column:formaDePagoID"`
|
FormaDePagoID uint `gorm:"column:formaDePagoID"`
|
||||||
FormaDePago FormaDePago `gorm:"foreignKey:FormaDePagoID"`
|
FormaDePago FormaDePago `gorm:"foreignKey:FormaDePagoID"`
|
||||||
ReciboID uint `json:"reciboId"`
|
ReciboID uint `json:"reciboId"`
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import "gorm.io/gorm"
|
|||||||
|
|
||||||
type Proveedor struct {
|
type Proveedor struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
Nombre string `gorm:"type:varchar(40)" json:"nombre"`
|
Nombre string `gorm:"type:varchar(40)" json:"nombre"`
|
||||||
Facturas []Factura `gorm:"foreignKey:ProveedorID" json:"facturas,omitempty"`
|
Facturas []Factura `gorm:"foreignKey:ProveedorID" json:"facturas,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -13,7 +13,7 @@ type Remito struct {
|
|||||||
EmisorID uint `gorm:"not null" json:"emisorId"`
|
EmisorID uint `gorm:"not null" json:"emisorId"`
|
||||||
ReceptorID uint `gorm:"not null" json:"receptorId"`
|
ReceptorID uint `gorm:"not null" json:"receptorId"`
|
||||||
|
|
||||||
AlmacenOrigenID *string `gorm:"column:almacen_origen_id;type:varchar(5)" json:"almacenOrigenId,omitempty"`
|
AlmacenOrigenID *uint `gorm:"column:almacen_origen_id" json:"almacenOrigenId,omitempty"`
|
||||||
AlmacenOrigen *Almacen `gorm:"foreignKey:AlmacenOrigenID" json:"almacenOrigen,omitempty"`
|
AlmacenOrigen *Almacen `gorm:"foreignKey:AlmacenOrigenID" json:"almacenOrigen,omitempty"`
|
||||||
|
|
||||||
Detalles datatypes.JSONSlice[RemitoDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
Detalles datatypes.JSONSlice[RemitoDetalle] `gorm:"type:json" json:"detalles,omitempty"`
|
||||||
|
|||||||
@@ -7,10 +7,11 @@ import (
|
|||||||
|
|
||||||
type Repuesto struct {
|
type Repuesto struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_repuesto_empresa_desc,priority:1" json:"empresaId"`
|
||||||
Nombre string `gorm:"type:varchar(50);not null" json:"nombre" binding:"required"`
|
Nombre string `gorm:"type:varchar(50);not null" json:"nombre" binding:"required"`
|
||||||
Precio float64 `gorm:"not null;type:decimal(10,2)" json:"precio" binding:"required"`
|
Precio float64 `gorm:"not null;type:decimal(10,2)" json:"precio" binding:"required"`
|
||||||
StockMinimo int64 `gorm:"not null;type:bigint" json:"stockMinimo" binding:"required"`
|
StockMinimo int64 `gorm:"not null;type:bigint" json:"stockMinimo" binding:"required"`
|
||||||
Descripcion string `gorm:"uniqueIndex;not null;type:varchar(70)" json:"descripcion" binding:"required"`
|
Descripcion string `gorm:"not null;type:varchar(70);uniqueIndex:uq_repuesto_empresa_desc,priority:2" json:"descripcion" binding:"required"`
|
||||||
MarcaID uint `gorm:"column:marcaID"`
|
MarcaID uint `gorm:"column:marcaID"`
|
||||||
Marca Marca `gorm:"foreignKey:MarcaID" json:"marca"`
|
Marca Marca `gorm:"foreignKey:MarcaID" json:"marca"`
|
||||||
Aliases datatypes.JSONSlice[string] `gorm:"type:json" json:"aliases,omitempty"`
|
Aliases datatypes.JSONSlice[string] `gorm:"type:json" json:"aliases,omitempty"`
|
||||||
|
|||||||
@@ -8,10 +8,11 @@ import (
|
|||||||
|
|
||||||
type Reserva struct {
|
type Reserva struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
EmpresaID uint `gorm:"not null;default:1;index;index:idx_reserva_empresa_repuesto_almacen,priority:1" json:"empresaId"`
|
||||||
|
|
||||||
RepuestoID uint `gorm:"not null;index:idx_reserva_repuesto_almacen" json:"repuesto_id"`
|
RepuestoID uint `gorm:"not null;index:idx_reserva_empresa_repuesto_almacen,priority:2" json:"repuesto_id"`
|
||||||
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto,omitempty"`
|
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto,omitempty"`
|
||||||
AlmacenID string `gorm:"type:varchar(5);not null;index:idx_reserva_repuesto_almacen" json:"almacen_id"`
|
AlmacenID uint `gorm:"not null;index:idx_reserva_empresa_repuesto_almacen,priority:3" json:"almacen_id"`
|
||||||
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
||||||
Cantidad float64 `gorm:"not null;check:cantidad > 0" json:"cantidad"`
|
Cantidad float64 `gorm:"not null;check:cantidad > 0" json:"cantidad"`
|
||||||
Estado EstadoReserva `gorm:"type:varchar(20);not null;default:'activa';index" json:"estado"`
|
Estado EstadoReserva `gorm:"type:varchar(20);not null;default:'activa';index" json:"estado"`
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package models_seguridad
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Empresa es el tenant del sistema. Todos los datos de negocio pertenecen a
|
||||||
|
// una empresa y se filtran por EmpresaID.
|
||||||
|
type Empresa struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
Nombre string `gorm:"type:varchar(120);not null" json:"nombre"`
|
||||||
|
Slug string `gorm:"type:varchar(60);uniqueIndex;not null" json:"slug"`
|
||||||
|
Cuit *string `gorm:"type:varchar(11);uniqueIndex" json:"cuit,omitempty"`
|
||||||
|
Activa bool `gorm:"not null;default:true" json:"activa"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (Empresa) TableName() string {
|
||||||
|
return "empresas"
|
||||||
|
}
|
||||||
|
|
||||||
|
type RolEmpresa string
|
||||||
|
|
||||||
|
const (
|
||||||
|
RolOwner RolEmpresa = "OWNER"
|
||||||
|
RolAdmin RolEmpresa = "ADMIN"
|
||||||
|
RolMiembro RolEmpresa = "MEMBER"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r RolEmpresa) Valido() bool {
|
||||||
|
switch r {
|
||||||
|
case RolOwner, RolAdmin, RolMiembro:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RolEmpresa) EsAdministrador() bool {
|
||||||
|
return r == RolOwner || r == RolAdmin
|
||||||
|
}
|
||||||
|
|
||||||
|
// EmpresaUsuario es la membresía de un usuario global dentro de una empresa.
|
||||||
|
type EmpresaUsuario struct {
|
||||||
|
EmpresaID uint `gorm:"primaryKey" json:"empresa_id"`
|
||||||
|
UsuarioID uint `gorm:"primaryKey" json:"usuario_id"`
|
||||||
|
Rol RolEmpresa `gorm:"type:varchar(20);not null;default:'MEMBER'" json:"rol"`
|
||||||
|
Activo bool `gorm:"not null;default:true" json:"activo"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
|
||||||
|
Empresa Empresa `gorm:"foreignKey:EmpresaID" json:"empresa,omitempty"`
|
||||||
|
Usuario Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (EmpresaUsuario) TableName() string {
|
||||||
|
return "empresa_usuarios"
|
||||||
|
}
|
||||||
|
|
||||||
|
type RolPlataforma string
|
||||||
|
|
||||||
|
const (
|
||||||
|
RolSuperadmin RolPlataforma = "SUPERADMIN"
|
||||||
|
RolSoporte RolPlataforma = "SOPORTE"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PlataformaAdmin es un rol transversal, separado de los grupos de cada
|
||||||
|
// empresa. No debe usarse para acceder a datos de negocio sin membresía.
|
||||||
|
type PlataformaAdmin struct {
|
||||||
|
UsuarioID uint `gorm:"primaryKey" json:"usuario_id"`
|
||||||
|
Rol RolPlataforma `gorm:"type:varchar(20);not null;default:'SUPERADMIN'" json:"rol"`
|
||||||
|
Activo bool `gorm:"not null;default:true" json:"activo"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
|
||||||
|
Usuario Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (PlataformaAdmin) TableName() string {
|
||||||
|
return "plataforma_admins"
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvitacionEmpresa permite sumar un usuario existente o crear uno nuevo en
|
||||||
|
// una empresa sin compartir contraseñas.
|
||||||
|
type InvitacionEmpresa struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
EmpresaID uint `gorm:"not null;index" json:"empresa_id"`
|
||||||
|
Email string `gorm:"type:varchar(100);not null;index" json:"email"`
|
||||||
|
Rol RolEmpresa `gorm:"type:varchar(20);not null;default:'MEMBER'" json:"rol"`
|
||||||
|
GrupoID uint `gorm:"not null;default:0" json:"grupo_id"`
|
||||||
|
TokenHash string `gorm:"type:varchar(64);uniqueIndex;not null" json:"-"`
|
||||||
|
ExpiraEn time.Time `gorm:"not null;index" json:"expira_en"`
|
||||||
|
UsadaEn *time.Time `json:"usada_en,omitempty"`
|
||||||
|
CreadaPor uint `gorm:"not null" json:"creada_por"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
|
||||||
|
Empresa Empresa `gorm:"foreignKey:EmpresaID" json:"empresa,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (InvitacionEmpresa) TableName() string {
|
||||||
|
return "invitaciones_empresa"
|
||||||
|
}
|
||||||
@@ -8,12 +8,13 @@ import (
|
|||||||
|
|
||||||
type Grupo struct {
|
type Grupo struct {
|
||||||
ID uint `gorm:"primaryKey" json:"id"`
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
Nombre string `gorm:"uniqueIndex;not null;type:varchar(100)" json:"nombre"`
|
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_grupo_empresa_nombre,priority:1" json:"empresaId"`
|
||||||
|
Nombre string `gorm:"not null;type:varchar(100);uniqueIndex:uq_grupo_empresa_nombre,priority:2" json:"nombre"`
|
||||||
Descripcion string `gorm:"type:text" json:"descripcion"`
|
Descripcion string `gorm:"type:text" json:"descripcion"`
|
||||||
Imagen string `gorm:"type:varchar(500)" json:"imagen"`
|
Imagen string `gorm:"type:varchar(500)" json:"imagen"`
|
||||||
Permisos []Permiso `gorm:"many2many:grupo_permisos;" json:"permisos,omitempty"`
|
Permisos []Permiso `gorm:"many2many:grupo_permisos;" json:"permisos,omitempty"`
|
||||||
Grupos []Grupo `gorm:"many2many:grupo_grupos;joinForeignKey:ParentGroupID;joinReferences:ChildGroupID" json:"grupos_hijos,omitempty"`
|
Grupos []Grupo `gorm:"many2many:grupo_grupos;joinForeignKey:ParentGroupID;joinReferences:ChildGroupID" json:"grupos_hijos,omitempty"`
|
||||||
Usuarios []Usuario `gorm:"many2many:usuario_grupos;" json:"usuarios,omitempty"`
|
Usuarios []Usuario `gorm:"many2many:usuarios_grupos;" json:"usuarios,omitempty"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package models_seguridad
|
||||||
|
|
||||||
|
// IDs estables del catálogo global de permisos. Se mantienen fijos para no
|
||||||
|
// romper tokens, grupos ni datos existentes.
|
||||||
|
const (
|
||||||
|
PermisoGestionPermisos uint = 1
|
||||||
|
PermisoGestionGrupos uint = 2
|
||||||
|
PermisoGestionUsuarios uint = 3
|
||||||
|
PermisoGestionRepuestos uint = 4
|
||||||
|
PermisoGestionLogs uint = 5
|
||||||
|
PermisoGestionMarcas uint = 6
|
||||||
|
PermisoGestionEmpresa uint = 7
|
||||||
|
PermisoPlataforma uint = 8
|
||||||
|
)
|
||||||
|
|
||||||
|
// PermisosDeEmpresa son los permisos que puede recibir una empresa. Los
|
||||||
|
// permisos de plataforma (1 y 8) nunca se asignan a grupos de tenant.
|
||||||
|
func PermisosDeEmpresa() []uint {
|
||||||
|
return []uint{
|
||||||
|
PermisoGestionGrupos,
|
||||||
|
PermisoGestionUsuarios,
|
||||||
|
PermisoGestionRepuestos,
|
||||||
|
PermisoGestionLogs,
|
||||||
|
PermisoGestionMarcas,
|
||||||
|
PermisoGestionEmpresa,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func EsPermisoDePlataforma(id uint) bool {
|
||||||
|
return id == PermisoGestionPermisos || id == PermisoPlataforma
|
||||||
|
}
|
||||||
@@ -11,8 +11,10 @@ type Usuario struct {
|
|||||||
Email string `gorm:"uniqueIndex;not null;type:varchar(100)" json:"email"`
|
Email string `gorm:"uniqueIndex;not null;type:varchar(100)" json:"email"`
|
||||||
Password string `gorm:"not null" json:"-"`
|
Password string `gorm:"not null" json:"-"`
|
||||||
Name string `gorm:"not null" json:"name"`
|
Name string `gorm:"not null" json:"name"`
|
||||||
|
Activo bool `gorm:"not null;default:true" json:"activo"`
|
||||||
|
DebeCambiarPassword bool `gorm:"not null;default:false" json:"-"`
|
||||||
Grupos []Grupo `gorm:"many2many:usuarios_grupos;" json:"grupos,omitempty"`
|
Grupos []Grupo `gorm:"many2many:usuarios_grupos;" json:"grupos,omitempty"`
|
||||||
// Empresas []Empresa `gorm:"many2many:user_empresa;" json:"empresas,omitempty"`
|
Empresas []Empresa `gorm:"many2many:empresa_usuarios;" json:"empresas,omitempty"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||||
|
|||||||
@@ -8,11 +8,13 @@ import (
|
|||||||
|
|
||||||
type Stock struct {
|
type Stock struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
|
EmpresaID uint64 `gorm:"not null;default:1;index;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:1" json:"empresaId"`
|
||||||
|
|
||||||
Cantidad uint `gorm:"not null;default:0" json:"cantidad"`
|
Cantidad uint `gorm:"not null;default:0" json:"cantidad"`
|
||||||
CantidadReservada uint `gorm:"not null:default:0" json:"cantidadReservada"`
|
CantidadReservada uint `gorm:"not null;default:0" json:"cantidadReservada"`
|
||||||
RepuestoID uint64 `gorm:"index;not null" json:"repuestoId"`
|
RepuestoID uint64 `gorm:"not null;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:2" json:"repuestoId"`
|
||||||
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto"`
|
Repuesto Repuesto `gorm:"foreignKey:RepuestoID" json:"repuesto"`
|
||||||
AlmacenID string `gorm:"type:varchar(5);index" json:"almacenId"`
|
AlmacenID uint `gorm:"not null;uniqueIndex:uq_stock_empresa_repuesto_almacen,priority:3" json:"almacenId"`
|
||||||
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
||||||
Observacion string `gorm:"type:varchar(60)" json:"observacion"`
|
Observacion string `gorm:"type:varchar(60)" json:"observacion"`
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ package repositorios
|
|||||||
import (
|
import (
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,32 +16,67 @@ type Repositorios struct {
|
|||||||
Repuesto RepositorioRepuesto
|
Repuesto RepositorioRepuesto
|
||||||
Marca RepositorioMarcas
|
Marca RepositorioMarcas
|
||||||
Logs RepositorioLogs
|
Logs RepositorioLogs
|
||||||
|
Empresa RepositorioEmpresa
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
instancia *Repositorios
|
instancia *Repositorios
|
||||||
|
dbGlobal *gorm.DB
|
||||||
once sync.Once
|
once sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
func InicializarRepositorios(db *gorm.DB) {
|
func InicializarRepositorios(db *gorm.DB) {
|
||||||
if instancia == nil {
|
if instancia == nil {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
instancia = &Repositorios{
|
dbGlobal = db
|
||||||
Permiso: &repositorioPermiso{db: db},
|
instancia = nuevoContenedor(db, 0)
|
||||||
Usuario: &repositorioUsuario{db: db},
|
|
||||||
Grupo: &repositorioGrupo{db: db},
|
|
||||||
Repuesto: NuevoRepositorioRepuesto(db),
|
|
||||||
Marca: NuevoRepositorioMarcas(db),
|
|
||||||
Logs: NuevoRepositorioLogs(db),
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ObtenerRepositorios() *Repositorios {
|
// ObtenerRepositorios devuelve el contenedor global. Si se pasa un contexto
|
||||||
|
// de Gin con empresa activa, devuelve un contenedor con los repositorios de
|
||||||
|
// negocio filtrados por esa empresa.
|
||||||
|
func ObtenerRepositorios(contextos ...*gin.Context) *Repositorios {
|
||||||
if instancia == nil {
|
if instancia == nil {
|
||||||
panic("los repositorios no fueron inicializados")
|
panic("los repositorios no fueron inicializados")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(contextos) == 0 || contextos[0] == nil {
|
||||||
return instancia
|
return instancia
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(contextos[0])
|
||||||
|
if empresaID == 0 {
|
||||||
|
return instancia
|
||||||
|
}
|
||||||
|
|
||||||
|
if cache, ok := contextos[0].Get("repositorios_empresa"); ok {
|
||||||
|
if repo, ok := cache.(*Repositorios); ok && repo != nil {
|
||||||
|
return repo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := nuevoContenedor(dbGlobal, empresaID)
|
||||||
|
contextos[0].Set("repositorios_empresa", repo)
|
||||||
|
return repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func nuevoContenedor(db *gorm.DB, empresaID uint) *Repositorios {
|
||||||
|
return &Repositorios{
|
||||||
|
Permiso: &repositorioPermiso{db: db},
|
||||||
|
Usuario: &repositorioUsuario{db: db, empresaID: empresaID},
|
||||||
|
Grupo: &repositorioGrupo{db: dbConEmpresa(db, empresaID), empresaID: empresaID},
|
||||||
|
Repuesto: NuevoRepositorioRepuesto(db, empresaID),
|
||||||
|
Marca: NuevoRepositorioMarcas(db, empresaID),
|
||||||
|
Logs: NuevoRepositorioLogs(db, empresaID),
|
||||||
|
Empresa: &repositorioEmpresa{db: db},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func dbConEmpresa(db *gorm.DB, empresaID uint) *gorm.DB {
|
||||||
|
if empresaID == 0 {
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
return db.Where("empresa_id = ?", empresaID)
|
||||||
}
|
}
|
||||||
@@ -24,13 +24,17 @@ type IRepositorio[T any] interface {
|
|||||||
|
|
||||||
type RepositorioBase[T any] struct {
|
type RepositorioBase[T any] struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRepositorioBase[T any](db *gorm.DB) *RepositorioBase[T] {
|
func NewRepositorioBase[T any](db *gorm.DB, empresaID uint) *RepositorioBase[T] {
|
||||||
return &RepositorioBase[T]{db: db}
|
return &RepositorioBase[T]{db: dbConEmpresa(db, empresaID), empresaID: empresaID}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *RepositorioBase[T]) Guardar(entidad *T) error {
|
func (r *RepositorioBase[T]) Guardar(entidad *T) error {
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
establecerEmpresaID(entidad, r.empresaID)
|
||||||
|
}
|
||||||
return r.db.Save(entidad).Error
|
return r.db.Save(entidad).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,6 +55,9 @@ func (r *RepositorioBase[T]) ObtenerPorID(id uint) (*T, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *RepositorioBase[T]) Crear(entidad T, usuarioID uint) error {
|
func (r *RepositorioBase[T]) Crear(entidad T, usuarioID uint) error {
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
establecerEmpresaID(&entidad, r.empresaID)
|
||||||
|
}
|
||||||
if err := r.db.Create(destinoConsulta(&entidad)).Error; err != nil {
|
if err := r.db.Create(destinoConsulta(&entidad)).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -70,6 +77,9 @@ func (r *RepositorioBase[T]) Actualizar(entidad *T, input T, usuarioID uint) err
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
establecerEmpresaID(&input, r.empresaID)
|
||||||
|
}
|
||||||
if err := r.db.Model(destinoConsulta(entidad)).Updates(input).Error; err != nil {
|
if err := r.db.Model(destinoConsulta(entidad)).Updates(input).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -117,6 +127,9 @@ func (r *RepositorioBase[T]) Alta(entidad *T, input T, usuarioID uint) error {
|
|||||||
if err := r.db.Unscoped().Model(modelo).Update("deleted_at", nil).Error; err != nil {
|
if err := r.db.Unscoped().Model(modelo).Update("deleted_at", nil).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
establecerEmpresaID(&input, r.empresaID)
|
||||||
|
}
|
||||||
if err := r.db.Unscoped().Model(modelo).Updates(input).Error; err != nil {
|
if err := r.db.Unscoped().Model(modelo).Updates(input).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -152,6 +165,9 @@ func (r *RepositorioBase[T]) registrarLog(log *models_logs.Log, err error, usuar
|
|||||||
if log == nil {
|
if log == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
log.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
if err := ObtenerRepositorios().Logs.Crear(log, usuarioID); err != nil {
|
if err := ObtenerRepositorios().Logs.Crear(log, usuarioID); err != nil {
|
||||||
applog.Printf("ERROR registrando log de %s: %v", contexto, err)
|
applog.Printf("ERROR registrando log de %s: %v", contexto, err)
|
||||||
}
|
}
|
||||||
@@ -183,3 +199,28 @@ func destinoConsulta[T any](entidad *T) any {
|
|||||||
}
|
}
|
||||||
return *entidad
|
return *entidad
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// establecerEmpresaID setea el campo EmpresaID de una entidad, si existe.
|
||||||
|
func establecerEmpresaID(dest any, empresaID uint) {
|
||||||
|
if empresaID == 0 || dest == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val := reflect.ValueOf(dest)
|
||||||
|
for val.IsValid() && val.Kind() == reflect.Ptr {
|
||||||
|
if val.IsNil() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val = val.Elem()
|
||||||
|
}
|
||||||
|
if !val.IsValid() || val.Kind() != reflect.Struct {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
campo := val.FieldByName("EmpresaID")
|
||||||
|
if !campo.IsValid() || !campo.CanSet() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch campo.Kind() {
|
||||||
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
campo.SetUint(uint64(empresaID))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,468 @@
|
|||||||
|
package repositorios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/config"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RepositorioEmpresa interface {
|
||||||
|
ObtenerPorID(id uint) (*models_seguridad.Empresa, error)
|
||||||
|
ObtenerPorSlug(slug string) (*models_seguridad.Empresa, error)
|
||||||
|
ListarTodas() ([]models_seguridad.Empresa, error)
|
||||||
|
ListarDeUsuario(usuarioID uint) ([]models_seguridad.Empresa, error)
|
||||||
|
Crear(empresa *models_seguridad.Empresa, ownerID uint) error
|
||||||
|
Actualizar(empresa *models_seguridad.Empresa, input models_seguridad.Empresa) error
|
||||||
|
Guardar(empresa *models_seguridad.Empresa) error
|
||||||
|
Desactivar(id uint) error
|
||||||
|
|
||||||
|
Membresia(empresaID, usuarioID uint) (*models_seguridad.EmpresaUsuario, error)
|
||||||
|
ListarMiembros(empresaID uint, pagina, tamano int) ([]models_seguridad.EmpresaUsuario, int64, error)
|
||||||
|
AgregarMiembro(empresaID, usuarioID uint, rol models_seguridad.RolEmpresa, grupoID uint) error
|
||||||
|
ActualizarRolMiembro(empresaID, usuarioID uint, rol models_seguridad.RolEmpresa) error
|
||||||
|
DesactivarMiembro(empresaID, usuarioID uint) error
|
||||||
|
EliminarMiembro(empresaID, usuarioID uint) error
|
||||||
|
ContarMiembros(empresaID uint) (int64, error)
|
||||||
|
ContarOwners(empresaID uint) (int64, error)
|
||||||
|
AsignarGrupoBase(empresaID, usuarioID uint, rol models_seguridad.RolEmpresa) error
|
||||||
|
|
||||||
|
CrearInvitacion(invitacion *models_seguridad.InvitacionEmpresa) (string, error)
|
||||||
|
ListarInvitaciones(empresaID uint) ([]models_seguridad.InvitacionEmpresa, error)
|
||||||
|
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 {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ObtenerPorID(id uint) (*models_seguridad.Empresa, error) {
|
||||||
|
var empresa models_seguridad.Empresa
|
||||||
|
if err := r.db.First(&empresa, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &empresa, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ObtenerPorSlug(slug string) (*models_seguridad.Empresa, error) {
|
||||||
|
var empresa models_seguridad.Empresa
|
||||||
|
if err := r.db.Where("slug = ?", slug).First(&empresa).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &empresa, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ListarTodas() ([]models_seguridad.Empresa, error) {
|
||||||
|
var empresas []models_seguridad.Empresa
|
||||||
|
if err := r.db.Order("nombre ASC").Find(&empresas).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return empresas, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ListarDeUsuario(usuarioID uint) ([]models_seguridad.Empresa, error) {
|
||||||
|
var empresas []models_seguridad.Empresa
|
||||||
|
err := r.db.Model(&models_seguridad.Empresa{}).
|
||||||
|
Joins("JOIN empresa_usuarios eu ON eu.empresa_id = empresas.id").
|
||||||
|
Where("eu.usuario_id = ? AND eu.activo = ?", usuarioID, true).
|
||||||
|
Where("empresas.activa = ? AND empresas.deleted_at IS NULL", true).
|
||||||
|
Order("empresas.nombre ASC").
|
||||||
|
Find(&empresas).Error
|
||||||
|
return empresas, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) Crear(empresa *models_seguridad.Empresa, ownerID uint) error {
|
||||||
|
if empresa.Nombre == "" {
|
||||||
|
return errors.New("el nombre de la empresa es obligatorio")
|
||||||
|
}
|
||||||
|
empresa.Slug = r.slugDisponible(empresa.Slug, empresa.Nombre)
|
||||||
|
empresa.Activa = true
|
||||||
|
|
||||||
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Create(empresa).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
adminID, _, err := config.AsegurarGruposEmpresa(tx, empresa.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if ownerID == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Create(&models_seguridad.EmpresaUsuario{
|
||||||
|
EmpresaID: empresa.ID,
|
||||||
|
UsuarioID: ownerID,
|
||||||
|
Rol: models_seguridad.RolOwner,
|
||||||
|
Activo: true,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Exec(
|
||||||
|
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) VALUES (?, ?)",
|
||||||
|
ownerID, adminID,
|
||||||
|
).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) Actualizar(empresa *models_seguridad.Empresa, input models_seguridad.Empresa) error {
|
||||||
|
if input.Nombre != "" {
|
||||||
|
empresa.Nombre = input.Nombre
|
||||||
|
}
|
||||||
|
if input.Slug != "" && input.Slug != empresa.Slug {
|
||||||
|
empresa.Slug = r.slugDisponible(input.Slug, input.Nombre)
|
||||||
|
}
|
||||||
|
if input.Cuit != nil {
|
||||||
|
empresa.Cuit = input.Cuit
|
||||||
|
}
|
||||||
|
return r.db.Save(empresa).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) Guardar(empresa *models_seguridad.Empresa) error {
|
||||||
|
return r.db.Save(empresa).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) Desactivar(id uint) error {
|
||||||
|
return r.db.Model(&models_seguridad.Empresa{}).Where("id = ?", id).Update("activa", false).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) Membresia(empresaID, usuarioID uint) (*models_seguridad.EmpresaUsuario, error) {
|
||||||
|
var membresia models_seguridad.EmpresaUsuario
|
||||||
|
if err := r.db.Preload("Usuario").
|
||||||
|
Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).
|
||||||
|
First(&membresia).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &membresia, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ListarMiembros(empresaID uint, pagina, tamano int) ([]models_seguridad.EmpresaUsuario, int64, error) {
|
||||||
|
if pagina < 0 {
|
||||||
|
pagina = 0
|
||||||
|
}
|
||||||
|
if tamano <= 0 || tamano > 100 {
|
||||||
|
tamano = 10
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
query := r.db.Model(&models_seguridad.EmpresaUsuario{}).Where("empresa_id = ?", empresaID)
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var miembros []models_seguridad.EmpresaUsuario
|
||||||
|
if err := query.
|
||||||
|
Preload("Usuario").
|
||||||
|
Order("usuario_id ASC").
|
||||||
|
Limit(tamano).
|
||||||
|
Offset(tamano * pagina).
|
||||||
|
Find(&miembros).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
return miembros, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) AgregarMiembro(empresaID, usuarioID uint, rol models_seguridad.RolEmpresa, grupoID uint) error {
|
||||||
|
if rol == "" {
|
||||||
|
rol = models_seguridad.RolMiembro
|
||||||
|
}
|
||||||
|
if !rol.Valido() {
|
||||||
|
return errors.New("rol inválido")
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var membresia models_seguridad.EmpresaUsuario
|
||||||
|
err := tx.Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).First(&membresia).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
membresia = models_seguridad.EmpresaUsuario{
|
||||||
|
EmpresaID: empresaID,
|
||||||
|
UsuarioID: usuarioID,
|
||||||
|
Rol: rol,
|
||||||
|
Activo: true,
|
||||||
|
}
|
||||||
|
if err := tx.Create(&membresia).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else if err != nil {
|
||||||
|
return err
|
||||||
|
} else if err := tx.Model(&membresia).Updates(map[string]any{"rol": rol, "activo": true}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
destino := grupoID
|
||||||
|
if destino == 0 {
|
||||||
|
adminID, usuarioGroupID, err := config.AsegurarGruposEmpresa(tx, empresaID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
destino = usuarioGroupID
|
||||||
|
if rol.EsAdministrador() {
|
||||||
|
destino = adminID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valida que el grupo pertenezca a la empresa cuando se indica uno.
|
||||||
|
if grupoID > 0 {
|
||||||
|
var grupo models_seguridad.Grupo
|
||||||
|
if err := tx.Where("id = ? AND empresa_id = ?", grupoID, empresaID).First(&grupo).Error; err != nil {
|
||||||
|
return errors.New("grupo inválido para la empresa")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Exec(
|
||||||
|
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) VALUES (?, ?)",
|
||||||
|
usuarioID, destino,
|
||||||
|
).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ActualizarRolMiembro(empresaID, usuarioID uint, rol models_seguridad.RolEmpresa) error {
|
||||||
|
if !rol.Valido() {
|
||||||
|
return errors.New("rol inválido")
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var membresia models_seguridad.EmpresaUsuario
|
||||||
|
if err := tx.Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).
|
||||||
|
First(&membresia).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Model(&membresia).Update("rol", rol).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
adminID, usuarioGroupID, err := config.AsegurarGruposEmpresa(tx, empresaID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
grupoDestino := usuarioGroupID
|
||||||
|
grupoQuitar := adminID
|
||||||
|
if rol.EsAdministrador() {
|
||||||
|
grupoDestino = adminID
|
||||||
|
grupoQuitar = usuarioGroupID
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Exec(
|
||||||
|
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) VALUES (?, ?)",
|
||||||
|
usuarioID, grupoDestino,
|
||||||
|
).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Exec(
|
||||||
|
"DELETE FROM usuarios_grupos WHERE usuario_id = ? AND grupo_id = ?",
|
||||||
|
usuarioID, grupoQuitar,
|
||||||
|
).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) DesactivarMiembro(empresaID, usuarioID uint) error {
|
||||||
|
return r.db.Model(&models_seguridad.EmpresaUsuario{}).
|
||||||
|
Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).
|
||||||
|
Update("activo", false).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) EliminarMiembro(empresaID, usuarioID uint) error {
|
||||||
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).
|
||||||
|
Delete(&models_seguridad.EmpresaUsuario{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Exec(`
|
||||||
|
DELETE ug FROM usuarios_grupos ug
|
||||||
|
JOIN groupos g ON g.id = ug.grupo_id
|
||||||
|
WHERE ug.usuario_id = ? AND g.empresa_id = ?
|
||||||
|
`, usuarioID, empresaID).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ContarMiembros(empresaID uint) (int64, error) {
|
||||||
|
var total int64
|
||||||
|
err := r.db.Model(&models_seguridad.EmpresaUsuario{}).
|
||||||
|
Where("empresa_id = ? AND activo = ?", empresaID, true).
|
||||||
|
Count(&total).Error
|
||||||
|
return total, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ContarOwners(empresaID uint) (int64, error) {
|
||||||
|
var total int64
|
||||||
|
err := r.db.Model(&models_seguridad.EmpresaUsuario{}).
|
||||||
|
Where("empresa_id = ? AND rol = ? AND activo = ?", empresaID, models_seguridad.RolOwner, true).
|
||||||
|
Count(&total).Error
|
||||||
|
return total, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// AsignarGrupoBase suma o cambia al usuario al grupo Admin/Usuario de la
|
||||||
|
// empresa según su rol, sin tocar otros grupos que tenga asignados.
|
||||||
|
func (r *repositorioEmpresa) AsignarGrupoBase(empresaID, usuarioID uint, rol models_seguridad.RolEmpresa) error {
|
||||||
|
adminID, usuarioIDGrupo, err := config.AsegurarGruposEmpresa(r.db, empresaID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
grupoID := usuarioIDGrupo
|
||||||
|
if rol.EsAdministrador() {
|
||||||
|
grupoID = adminID
|
||||||
|
}
|
||||||
|
return r.db.Exec(
|
||||||
|
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) VALUES (?, ?)",
|
||||||
|
usuarioID, grupoID,
|
||||||
|
).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) CrearInvitacion(invitacion *models_seguridad.InvitacionEmpresa) (string, error) {
|
||||||
|
if invitacion.Email == "" {
|
||||||
|
return "", errors.New("el email es obligatorio")
|
||||||
|
}
|
||||||
|
if !invitacion.Rol.Valido() {
|
||||||
|
invitacion.Rol = models_seguridad.RolMiembro
|
||||||
|
}
|
||||||
|
if invitacion.ExpiraEn.IsZero() {
|
||||||
|
invitacion.ExpiraEn = time.Now().Add(7 * 24 * time.Hour)
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := tokenAleatorio()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
invitacion.TokenHash = hashToken(token)
|
||||||
|
|
||||||
|
// Una sola invitación vigente por email y empresa.
|
||||||
|
if err := r.db.Where("empresa_id = ? AND email = ? AND usada_en IS NULL", invitacion.EmpresaID, invitacion.Email).
|
||||||
|
Delete(&models_seguridad.InvitacionEmpresa{}).Error; err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.db.Create(invitacion).Error; err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ListarInvitaciones(empresaID uint) ([]models_seguridad.InvitacionEmpresa, error) {
|
||||||
|
var invitaciones []models_seguridad.InvitacionEmpresa
|
||||||
|
err := r.db.Where("empresa_id = ?", empresaID).
|
||||||
|
Order("created_at DESC").
|
||||||
|
Find(&invitaciones).Error
|
||||||
|
return invitaciones, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) ObtenerInvitacionPorToken(token string) (*models_seguridad.InvitacionEmpresa, error) {
|
||||||
|
var invitacion models_seguridad.InvitacionEmpresa
|
||||||
|
if err := r.db.Preload("Empresa").
|
||||||
|
Where("token_hash = ?", hashToken(token)).
|
||||||
|
First(&invitacion).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &invitacion, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) MarcarInvitacionUsada(id uint) error {
|
||||||
|
now := time.Now()
|
||||||
|
return r.db.Model(&models_seguridad.InvitacionEmpresa{}).
|
||||||
|
Where("id = ? AND usada_en IS NULL", id).
|
||||||
|
Update("usada_en", &now).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioEmpresa) EliminarInvitacion(empresaID, id uint) error {
|
||||||
|
return r.db.Where("empresa_id = ? AND id = ?", empresaID, id).
|
||||||
|
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 == "" {
|
||||||
|
base = config.Slugify(nombre)
|
||||||
|
}
|
||||||
|
if base == "" {
|
||||||
|
base = "empresa"
|
||||||
|
}
|
||||||
|
|
||||||
|
candidato := base
|
||||||
|
for i := 2; i < 1000; i++ {
|
||||||
|
var count int64
|
||||||
|
r.db.Model(&models_seguridad.Empresa{}).Where("slug = ?", candidato).Count(&count)
|
||||||
|
if count == 0 {
|
||||||
|
return candidato
|
||||||
|
}
|
||||||
|
candidato = fmt.Sprintf("%s-%d", base, i)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s-%d", base, time.Now().Unix())
|
||||||
|
}
|
||||||
|
|
||||||
|
func tokenAleatorio() (string, error) {
|
||||||
|
bytes := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(bytes); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(bytes), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashToken(token string) string {
|
||||||
|
sum := sha256.Sum256([]byte(strings.TrimSpace(token)))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
package repositorios
|
package repositorios
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"repuestera_back/config"
|
||||||
|
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -22,39 +26,57 @@ type RepositorioGrupo interface {
|
|||||||
|
|
||||||
type repositorioGrupo struct {
|
type repositorioGrupo struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioGrupo) scopedDB() *gorm.DB {
|
||||||
|
db := config.DB
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
db = db.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) ObtenerTodosConRelaciones() ([]models_seguridad.Grupo, error) {
|
func (r *repositorioGrupo) ObtenerTodosConRelaciones() ([]models_seguridad.Grupo, error) {
|
||||||
var grupos []models_seguridad.Grupo
|
var grupos []models_seguridad.Grupo
|
||||||
if err := r.db.Preload("Permisos").Find(&grupos).Error; err != nil {
|
if err := r.scopedDB().Preload("Permisos").Find(&grupos).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
for i := range grupos {
|
for i := range grupos {
|
||||||
r.db.Model(&grupos[i]).Association("Grupos").Find(&grupos[i].Grupos)
|
if err := r.cargarGruposRecursivo(&grupos[i], false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return grupos, nil
|
return grupos, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) cargarGruposRecursivo(grupo *models_seguridad.Grupo, simple bool) error {
|
func (r *repositorioGrupo) cargarGruposRecursivo(grupo *models_seguridad.Grupo, simple bool) error {
|
||||||
if simple {
|
if simple {
|
||||||
if err := r.db.
|
err := r.scopedDB().
|
||||||
Model(grupo).
|
Model(grupo).
|
||||||
Preload("Permisos", func(db *gorm.DB) *gorm.DB {
|
Preload("Permisos", func(db *gorm.DB) *gorm.DB {
|
||||||
return db.Select("id", "nombre", "alias", "imagen")
|
return db.Select("id", "nombre", "alias", "imagen")
|
||||||
}).
|
}).
|
||||||
Association("Grupos").
|
Association("Grupos").
|
||||||
Find(&grupo.Grupos); err != nil {
|
Find(&grupo.Grupos)
|
||||||
|
if err != nil {
|
||||||
|
// GORM devuelve record not found cuando no hay subgrupos; no es error.
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) && err.Error() != "record not found" {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
if err := r.db.
|
err := r.scopedDB().
|
||||||
Model(grupo).
|
Model(grupo).
|
||||||
Preload("Permisos").
|
Preload("Permisos").
|
||||||
Association("Grupos").
|
Association("Grupos").
|
||||||
Find(&grupo.Grupos); err != nil {
|
Find(&grupo.Grupos)
|
||||||
|
if err != nil {
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) && err.Error() != "record not found" {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for i := range grupo.Grupos {
|
for i := range grupo.Grupos {
|
||||||
if err := r.cargarGruposRecursivo(
|
if err := r.cargarGruposRecursivo(
|
||||||
@@ -72,7 +94,7 @@ func (r *repositorioGrupo) ObtenerPorIDConRelaciones(id uint, simple bool) (*mod
|
|||||||
var grupo models_seguridad.Grupo
|
var grupo models_seguridad.Grupo
|
||||||
|
|
||||||
if simple {
|
if simple {
|
||||||
if err := r.db.
|
if err := r.scopedDB().
|
||||||
Preload("Permisos", func(db *gorm.DB) *gorm.DB {
|
Preload("Permisos", func(db *gorm.DB) *gorm.DB {
|
||||||
return db.Select("id", "nombre", "alias", "imagen")
|
return db.Select("id", "nombre", "alias", "imagen")
|
||||||
}).
|
}).
|
||||||
@@ -80,7 +102,7 @@ func (r *repositorioGrupo) ObtenerPorIDConRelaciones(id uint, simple bool) (*mod
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if err := r.db.
|
if err := r.scopedDB().
|
||||||
Preload("Permisos").
|
Preload("Permisos").
|
||||||
First(&grupo, id).Error; err != nil {
|
First(&grupo, id).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -96,78 +118,77 @@ func (r *repositorioGrupo) ObtenerPorIDConRelaciones(id uint, simple bool) (*mod
|
|||||||
|
|
||||||
func (r *repositorioGrupo) ObtenerPorID(id uint) (*models_seguridad.Grupo, error) {
|
func (r *repositorioGrupo) ObtenerPorID(id uint) (*models_seguridad.Grupo, error) {
|
||||||
var grupo models_seguridad.Grupo
|
var grupo models_seguridad.Grupo
|
||||||
if err := r.db.First(&grupo, id).Error; err != nil {
|
if err := r.scopedDB().First(&grupo, id).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &grupo, nil
|
return &grupo, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) Crear(grupo *models_seguridad.Grupo) error {
|
func (r *repositorioGrupo) Crear(grupo *models_seguridad.Grupo) error {
|
||||||
return r.db.Create(grupo).Error
|
if r.empresaID > 0 {
|
||||||
|
grupo.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
|
return r.scopedDB().Create(grupo).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) Actualizar(grupo *models_seguridad.Grupo, input models_seguridad.Grupo) error {
|
func (r *repositorioGrupo) Actualizar(grupo *models_seguridad.Grupo, input models_seguridad.Grupo) error {
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
input.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
// Select explicito para persistir tambien los valores cero (por ejemplo,
|
// Select explicito para persistir tambien los valores cero (por ejemplo,
|
||||||
// quitar la imagen de un grupo).
|
// quitar la imagen de un grupo).
|
||||||
return r.db.Model(grupo).Select("Nombre", "Descripcion", "Imagen").Updates(input).Error
|
return r.scopedDB().Model(grupo).Select("EmpresaID", "Nombre", "Descripcion", "Imagen").Updates(input).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) Eliminar(id uint) error {
|
func (r *repositorioGrupo) Eliminar(id uint) error {
|
||||||
return r.db.Delete(&models_seguridad.Grupo{}, id).Error
|
return r.scopedDB().Delete(&models_seguridad.Grupo{}, id).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) AgregarPermiso(grupoID, permisoID uint) error {
|
func (r *repositorioGrupo) AgregarPermiso(grupoID, permisoID uint) error {
|
||||||
var grupo models_seguridad.Grupo
|
var grupo models_seguridad.Grupo
|
||||||
if err := r.db.First(&grupo, grupoID).Error; err != nil {
|
if err := r.scopedDB().First(&grupo, grupoID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var permiso models_seguridad.Permiso
|
var permiso models_seguridad.Permiso
|
||||||
if err := r.db.First(&permiso, permisoID).Error; err != nil {
|
if err := r.scopedDB().First(&permiso, permisoID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return r.db.Model(&grupo).Association("Permisos").Append(&permiso)
|
return r.scopedDB().Model(&grupo).Association("Permisos").Append(&permiso)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) QuitarPermiso(grupoID, permisoID uint) error {
|
func (r *repositorioGrupo) QuitarPermiso(grupoID, permisoID uint) error {
|
||||||
var grupo models_seguridad.Grupo
|
var grupo models_seguridad.Grupo
|
||||||
if err := r.db.First(&grupo, grupoID).Error; err != nil {
|
if err := r.scopedDB().First(&grupo, grupoID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var permiso models_seguridad.Permiso
|
var permiso models_seguridad.Permiso
|
||||||
if err := r.db.First(&permiso, permisoID).Error; err != nil {
|
if err := r.scopedDB().First(&permiso, permisoID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return r.db.Model(&grupo).Association("Permisos").Delete(&permiso)
|
return r.scopedDB().Model(&grupo).Association("Permisos").Delete(&permiso)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) AgregarSubGrupo(padreID, hijoID uint) error {
|
func (r *repositorioGrupo) AgregarSubGrupo(padreID, hijoID uint) error {
|
||||||
var padre models_seguridad.Grupo
|
var padre models_seguridad.Grupo
|
||||||
if err := r.db.Preload("Grupos").First(&padre, padreID).Error; err != nil {
|
if err := r.scopedDB().Preload("Grupos").First(&padre, padreID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
padre.Grupos = append(padre.Grupos, models_seguridad.Grupo{ID: hijoID})
|
var hijo models_seguridad.Grupo
|
||||||
return r.db.Save(&padre).Error
|
if err := r.scopedDB().First(&hijo, hijoID).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if padre.ID == hijo.ID {
|
||||||
|
return errors.New("un grupo no puede ser subgrupo de si mismo")
|
||||||
|
}
|
||||||
|
padre.Grupos = append(padre.Grupos, hijo)
|
||||||
|
return r.scopedDB().Save(&padre).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioGrupo) QuitarSubGrupo(padreID, hijoID uint) error {
|
func (r *repositorioGrupo) QuitarSubGrupo(padreID, hijoID uint) error {
|
||||||
// var padre models_seguridad.Grupo
|
|
||||||
// if err := r.db.Preload("Grupos").First(&padre, padreID).Error; err != nil {
|
|
||||||
// return err
|
|
||||||
// }
|
|
||||||
|
|
||||||
var padre models_seguridad.Grupo
|
var padre models_seguridad.Grupo
|
||||||
if err := r.db.Preload("Grupos").First(&padre, padreID).Error; err != nil {
|
if err := r.scopedDB().Preload("Grupos").First(&padre, padreID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return r.db.Model(&padre).Association("Grupos").Delete(&models_seguridad.Grupo{ID: hijoID})
|
return r.scopedDB().Model(&padre).Association("Grupos").Delete(&models_seguridad.Grupo{ID: hijoID})
|
||||||
|
|
||||||
// var nuevos []models_seguridad.Grupo
|
|
||||||
// for _, g := range padre.Grupos {
|
|
||||||
// if g.ID != hijoID {
|
|
||||||
// nuevos = append(nuevos, g)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// padre.Grupos = nuevos
|
|
||||||
// return r.db.Save(&padre).Error
|
|
||||||
}
|
}
|
||||||
@@ -18,24 +18,29 @@ type RepositorioLogs interface {
|
|||||||
type repositorioLogs struct {
|
type repositorioLogs struct {
|
||||||
*RepositorioBase[*logs.Log]
|
*RepositorioBase[*logs.Log]
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
}
|
}
|
||||||
|
|
||||||
func NuevoRepositorioLogs(db *gorm.DB) RepositorioLogs {
|
func NuevoRepositorioLogs(db *gorm.DB, empresaID uint) RepositorioLogs {
|
||||||
baseRepo := NewRepositorioBase[*logs.Log](db)
|
baseRepo := NewRepositorioBase[*logs.Log](db, empresaID)
|
||||||
return &repositorioLogs{
|
return &repositorioLogs{
|
||||||
RepositorioBase: baseRepo,
|
RepositorioBase: baseRepo,
|
||||||
db: db,
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crear persiste el log directamente, sin auditar la creación del propio log.
|
// Crear persiste el log directamente, sin auditar la creación del propio log.
|
||||||
func (r *repositorioLogs) Crear(entidad *logs.Log, usuarioID uint) error {
|
func (r *repositorioLogs) Crear(entidad *logs.Log, usuarioID uint) error {
|
||||||
|
if r.empresaID > 0 && entidad.EmpresaID == 0 {
|
||||||
|
entidad.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
return r.db.Create(entidad).Error
|
return r.db.Create(entidad).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioLogs) ObtenerPorPaginas(pag uint) ([]logs.Log, error) {
|
func (r *repositorioLogs) ObtenerPorPaginas(pag uint) ([]logs.Log, error) {
|
||||||
var logs []logs.Log
|
var logs []logs.Log
|
||||||
if err := r.db.Limit(10).Offset(int(pag) * 10).Find(&logs).Error; err != nil {
|
if err := r.db.Preload("Usuario").Limit(10).Offset(int(pag) * 10).Find(&logs).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return logs, nil
|
return logs, nil
|
||||||
@@ -72,6 +77,7 @@ func (r *repositorioLogs) ObtenerConFiltros(p int, f dto.BusquedaLogsDto) ([]log
|
|||||||
}
|
}
|
||||||
|
|
||||||
err := db.
|
err := db.
|
||||||
|
Preload("Usuario").
|
||||||
Limit(10).
|
Limit(10).
|
||||||
Offset(10 * p).
|
Offset(10 * p).
|
||||||
Find(&logss).Error
|
Find(&logss).Error
|
||||||
|
|||||||
@@ -15,13 +15,15 @@ type RepositorioMarcas interface {
|
|||||||
type repositorioMarcas struct {
|
type repositorioMarcas struct {
|
||||||
*RepositorioBase[models.Marca]
|
*RepositorioBase[models.Marca]
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
}
|
}
|
||||||
|
|
||||||
func NuevoRepositorioMarcas(db *gorm.DB) RepositorioMarcas {
|
func NuevoRepositorioMarcas(db *gorm.DB, empresaID uint) RepositorioMarcas {
|
||||||
baseRepo := NewRepositorioBase[models.Marca](db)
|
baseRepo := NewRepositorioBase[models.Marca](db, empresaID)
|
||||||
return &repositorioMarcas{
|
return &repositorioMarcas{
|
||||||
RepositorioBase: baseRepo,
|
RepositorioBase: baseRepo,
|
||||||
db: db,
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +36,9 @@ func (r *repositorioMarcas) ObtenerPorNombre(nombre string) (*models.Marca, erro
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioMarcas) CrearFaltante(marca models.Marca) error {
|
func (r *repositorioMarcas) CrearFaltante(marca models.Marca) error {
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
marca.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
var marcaa models.Marca
|
var marcaa models.Marca
|
||||||
if err := r.db.Where("nombre = ?", marca.Nombre).First(&marcaa).Error; err != nil {
|
if err := r.db.Where("nombre = ?", marca.Nombre).First(&marcaa).Error; err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
|
|||||||
@@ -16,19 +16,25 @@ type RepositorioRepuesto interface {
|
|||||||
type repositorioRepuesto struct {
|
type repositorioRepuesto struct {
|
||||||
*RepositorioBase[*models.Repuesto]
|
*RepositorioBase[*models.Repuesto]
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
}
|
}
|
||||||
|
|
||||||
func NuevoRepositorioRepuesto(db *gorm.DB) RepositorioRepuesto {
|
func NuevoRepositorioRepuesto(db *gorm.DB, empresaID uint) RepositorioRepuesto {
|
||||||
baseRepo := NewRepositorioBase[*models.Repuesto](db)
|
baseRepo := NewRepositorioBase[*models.Repuesto](db, empresaID)
|
||||||
return &repositorioRepuesto{
|
return &repositorioRepuesto{
|
||||||
RepositorioBase: baseRepo,
|
RepositorioBase: baseRepo,
|
||||||
db: db,
|
db: dbConEmpresa(db, empresaID),
|
||||||
|
empresaID: empresaID,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r repositorioRepuesto) ObtenerTodosConMarca() ([]*models.Repuesto, error) {
|
func (r repositorioRepuesto) ObtenerTodosConMarca() ([]*models.Repuesto, error) {
|
||||||
var repuestos []*models.Repuesto
|
var repuestos []*models.Repuesto
|
||||||
if err := r.db.Unscoped().Preload("Marca").Find(&repuestos).Error; err != nil {
|
query := r.db.Unscoped().Preload("Marca")
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Preload("Marca", "empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.Find(&repuestos).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return repuestos, nil
|
return repuestos, nil
|
||||||
@@ -38,6 +44,7 @@ func (r repositorioRepuesto) ObtenerTodosConMarca() ([]*models.Repuesto, error)
|
|||||||
func (r repositorioRepuesto) AltaRepuesto(id uint, uid uint) (*models.Repuesto, error) {
|
func (r repositorioRepuesto) AltaRepuesto(id uint, uid uint) (*models.Repuesto, error) {
|
||||||
rep := models.Repuesto{
|
rep := models.Repuesto{
|
||||||
ID: uint(id),
|
ID: uint(id),
|
||||||
|
EmpresaID: r.empresaID,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
@@ -49,6 +56,7 @@ func (r repositorioRepuesto) AltaRepuesto(id uint, uid uint) (*models.Repuesto,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
log.EmpresaID = r.empresaID
|
||||||
|
|
||||||
if err := tx.Create(log).Error; err != nil {
|
if err := tx.Create(log).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -61,5 +69,4 @@ func (r repositorioRepuesto) AltaRepuesto(id uint, uid uint) (*models.Repuesto,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &rep, nil
|
return &rep, nil
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -12,11 +12,18 @@ type RepositorioUsuario interface {
|
|||||||
BuscarPorID(id uint) (*models_seguridad.Usuario, error)
|
BuscarPorID(id uint) (*models_seguridad.Usuario, error)
|
||||||
ObtenerPorEmail(email string) (*models_seguridad.Usuario, error)
|
ObtenerPorEmail(email string) (*models_seguridad.Usuario, error)
|
||||||
Crear(usuario *models_seguridad.Usuario) error
|
Crear(usuario *models_seguridad.Usuario) error
|
||||||
ActualizarContraseña(id uint, hashedPassword string) error
|
ActualizarContraseña(id uint, hashedPassword string, debeCambiar bool) error
|
||||||
ObtenerTodosPaginado(pagina, tamaño int) ([]models_seguridad.Usuario, int64, error)
|
ObtenerTodosPaginado(pagina, tamaño int) ([]models_seguridad.Usuario, int64, error)
|
||||||
|
ListarGlobales(pagina, tamaño int) ([]models_seguridad.Usuario, int64, error)
|
||||||
Guardar(usuario *models_seguridad.Usuario) error
|
Guardar(usuario *models_seguridad.Usuario) error
|
||||||
Eliminar(id uint) error
|
Eliminar(id uint) error
|
||||||
|
QuitarDeEmpresa(usuarioID uint) error
|
||||||
|
ObtenerMembresia(usuarioID uint) (*models_seguridad.EmpresaUsuario, error)
|
||||||
|
ObtenerEmpresasDeUsuario(usuarioID uint) ([]models_seguridad.Empresa, error)
|
||||||
|
EsMiembro(usuarioID uint) (bool, error)
|
||||||
|
CantidadMiembros() (int64, error)
|
||||||
PrecargarGruposPermisosPorID(id uint) (*models_seguridad.Usuario, error)
|
PrecargarGruposPermisosPorID(id uint) (*models_seguridad.Usuario, error)
|
||||||
|
PrecargarGruposPermisosDeEmpresa(usuarioID, empresaID uint) (*models_seguridad.Usuario, error)
|
||||||
ObtenerPorEmailConGrupos(email string) (*models_seguridad.Usuario, error)
|
ObtenerPorEmailConGrupos(email string) (*models_seguridad.Usuario, error)
|
||||||
ObtenerGruposPorUsuarioID(usuarioID uint) ([]models_seguridad.Grupo, error)
|
ObtenerGruposPorUsuarioID(usuarioID uint) ([]models_seguridad.Grupo, error)
|
||||||
AgregarGrupoAUsuario(usuarioID, grupoID uint) error
|
AgregarGrupoAUsuario(usuarioID, grupoID uint) error
|
||||||
@@ -26,6 +33,7 @@ type RepositorioUsuario interface {
|
|||||||
|
|
||||||
type repositorioUsuario struct {
|
type repositorioUsuario struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
empresaID uint
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioUsuario) CantidadUsuarios(cant *int64) error {
|
func (r *repositorioUsuario) CantidadUsuarios(cant *int64) error {
|
||||||
@@ -35,6 +43,14 @@ func (r *repositorioUsuario) CantidadUsuarios(cant *int64) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *repositorioUsuario) CantidadMiembros() (int64, error) {
|
||||||
|
var cant int64
|
||||||
|
err := r.db.Model(&models_seguridad.EmpresaUsuario{}).
|
||||||
|
Where("empresa_id = ? AND activo = ?", r.empresaID, true).
|
||||||
|
Count(&cant).Error
|
||||||
|
return cant, err
|
||||||
|
}
|
||||||
|
|
||||||
func (r *repositorioUsuario) ObtenerPorID(id uint) (*models_seguridad.Usuario, error) {
|
func (r *repositorioUsuario) ObtenerPorID(id uint) (*models_seguridad.Usuario, error) {
|
||||||
var user models_seguridad.Usuario
|
var user models_seguridad.Usuario
|
||||||
if err := r.db.First(&user, id).Error; err != nil {
|
if err := r.db.First(&user, id).Error; err != nil {
|
||||||
@@ -63,22 +79,47 @@ func (r *repositorioUsuario) Crear(usuario *models_seguridad.Usuario) error {
|
|||||||
return r.db.Create(usuario).Error
|
return r.db.Create(usuario).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioUsuario) ActualizarContraseña(id uint, hashedPassword string) error {
|
func (r *repositorioUsuario) ActualizarContraseña(id uint, hashedPassword string, debeCambiar bool) error {
|
||||||
return r.db.Model(&models_seguridad.Usuario{}).Where("id = ?", id).Update("password", hashedPassword).Error
|
return r.db.Model(&models_seguridad.Usuario{}).Where("id = ?", id).
|
||||||
|
Updates(map[string]any{"password": hashedPassword, "debe_cambiar_password": debeCambiar}).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioUsuario) ObtenerTodosPaginado(pagina, tamaño int) ([]models_seguridad.Usuario, int64, error) {
|
func (r *repositorioUsuario) ObtenerTodosPaginado(pagina, tamaño int) ([]models_seguridad.Usuario, int64, error) {
|
||||||
var usuarios []models_seguridad.Usuario
|
var usuarios []models_seguridad.Usuario
|
||||||
var total int64
|
var total int64
|
||||||
|
|
||||||
|
query := r.db.Model(&models_seguridad.Usuario{}).
|
||||||
|
Joins("JOIN empresa_usuarios eu ON eu.usuario_id = usuarios.id").
|
||||||
|
Where("eu.empresa_id = ? AND eu.activo = ?", r.empresaID, true)
|
||||||
|
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := query.Limit(tamaño).Offset(tamaño * pagina).Find(&usuarios).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return usuarios, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioUsuario) ListarGlobales(pagina, tamaño int) ([]models_seguridad.Usuario, int64, error) {
|
||||||
|
if pagina < 0 {
|
||||||
|
pagina = 0
|
||||||
|
}
|
||||||
|
if tamaño <= 0 || tamaño > 100 {
|
||||||
|
tamaño = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
if err := r.db.Model(&models_seguridad.Usuario{}).Count(&total).Error; err != nil {
|
if err := r.db.Model(&models_seguridad.Usuario{}).Count(&total).Error; err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.db.Limit(tamaño).Offset(tamaño * pagina).Find(&usuarios).Error; err != nil {
|
var usuarios []models_seguridad.Usuario
|
||||||
|
if err := r.db.Order("id ASC").Limit(tamaño).Offset(tamaño * pagina).Find(&usuarios).Error; err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return usuarios, total, nil
|
return usuarios, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,6 +131,37 @@ func (r *repositorioUsuario) Eliminar(id uint) error {
|
|||||||
return r.db.Delete(&models_seguridad.Usuario{}, id).Error
|
return r.db.Delete(&models_seguridad.Usuario{}, id).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *repositorioUsuario) QuitarDeEmpresa(usuarioID uint) error {
|
||||||
|
return r.db.Where("usuario_id = ? AND empresa_id = ?", usuarioID, r.empresaID).
|
||||||
|
Delete(&models_seguridad.EmpresaUsuario{}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioUsuario) ObtenerMembresia(usuarioID uint) (*models_seguridad.EmpresaUsuario, error) {
|
||||||
|
var membresia models_seguridad.EmpresaUsuario
|
||||||
|
if err := r.db.Where("usuario_id = ? AND empresa_id = ?", usuarioID, r.empresaID).
|
||||||
|
First(&membresia).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &membresia, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioUsuario) ObtenerEmpresasDeUsuario(usuarioID uint) ([]models_seguridad.Empresa, error) {
|
||||||
|
var empresas []models_seguridad.Empresa
|
||||||
|
err := r.db.Model(&models_seguridad.Empresa{}).
|
||||||
|
Joins("JOIN empresa_usuarios eu ON eu.empresa_id = empresas.id").
|
||||||
|
Where("eu.usuario_id = ? AND eu.activo = ?", usuarioID, true).
|
||||||
|
Find(&empresas).Error
|
||||||
|
return empresas, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioUsuario) EsMiembro(usuarioID uint) (bool, error) {
|
||||||
|
var count int64
|
||||||
|
err := r.db.Model(&models_seguridad.EmpresaUsuario{}).
|
||||||
|
Where("usuario_id = ? AND empresa_id = ? AND activo = ?", usuarioID, r.empresaID, true).
|
||||||
|
Count(&count).Error
|
||||||
|
return count > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
func (r *repositorioUsuario) cargarGruposPermisosRecursivo(grupo *models_seguridad.Grupo, visitados map[uint]bool) error {
|
func (r *repositorioUsuario) cargarGruposPermisosRecursivo(grupo *models_seguridad.Grupo, visitados map[uint]bool) error {
|
||||||
if visitados[grupo.ID] {
|
if visitados[grupo.ID] {
|
||||||
// Evita ciclos en la jerarquia de grupos.
|
// Evita ciclos en la jerarquia de grupos.
|
||||||
@@ -98,11 +170,11 @@ func (r *repositorioUsuario) cargarGruposPermisosRecursivo(grupo *models_segurid
|
|||||||
}
|
}
|
||||||
visitados[grupo.ID] = true
|
visitados[grupo.ID] = true
|
||||||
|
|
||||||
if err := r.db.
|
query := r.db.Model(grupo).Preload("Permisos")
|
||||||
Model(grupo).
|
if r.empresaID > 0 {
|
||||||
Preload("Permisos").
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
Association("Grupos").
|
}
|
||||||
Find(&grupo.Grupos); err != nil {
|
if err := query.Association("Grupos").Find(&grupo.Grupos); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,7 +189,11 @@ func (r *repositorioUsuario) cargarGruposPermisosRecursivo(grupo *models_segurid
|
|||||||
|
|
||||||
func (r *repositorioUsuario) PrecargarGruposPermisosPorID(id uint) (*models_seguridad.Usuario, error) {
|
func (r *repositorioUsuario) PrecargarGruposPermisosPorID(id uint) (*models_seguridad.Usuario, error) {
|
||||||
var user models_seguridad.Usuario
|
var user models_seguridad.Usuario
|
||||||
if err := r.db.Preload("Grupos.Permisos").First(&user, id).Error; err != nil {
|
query := r.db.Preload("Grupos.Permisos")
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Preload("Grupos", "empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.First(&user, id).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,9 +207,54 @@ func (r *repositorioUsuario) PrecargarGruposPermisosPorID(id uint) (*models_segu
|
|||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *repositorioUsuario) PrecargarGruposPermisosDeEmpresa(usuarioID, empresaID uint) (*models_seguridad.Usuario, error) {
|
||||||
|
var user models_seguridad.Usuario
|
||||||
|
query := r.db.Preload("Grupos", func(db *gorm.DB) *gorm.DB {
|
||||||
|
return db.Where("empresa_id = ?", empresaID).Preload("Permisos")
|
||||||
|
})
|
||||||
|
if err := query.First(&user, usuarioID).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
visitados := make(map[uint]bool)
|
||||||
|
for i := range user.Grupos {
|
||||||
|
if err := r.cargarGruposPermisosRecursivoEmpresa(&user.Grupos[i], visitados, empresaID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repositorioUsuario) cargarGruposPermisosRecursivoEmpresa(grupo *models_seguridad.Grupo, visitados map[uint]bool, empresaID uint) error {
|
||||||
|
if visitados[grupo.ID] {
|
||||||
|
grupo.Grupos = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
visitados[grupo.ID] = true
|
||||||
|
|
||||||
|
query := r.db.Model(grupo).
|
||||||
|
Where("empresa_id = ?", empresaID).
|
||||||
|
Preload("Permisos")
|
||||||
|
if err := query.Association("Grupos").Find(&grupo.Grupos); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range grupo.Grupos {
|
||||||
|
if err := r.cargarGruposPermisosRecursivoEmpresa(&grupo.Grupos[i], visitados, empresaID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (r *repositorioUsuario) ObtenerPorEmailConGrupos(email string) (*models_seguridad.Usuario, error) {
|
func (r *repositorioUsuario) ObtenerPorEmailConGrupos(email string) (*models_seguridad.Usuario, error) {
|
||||||
var user models_seguridad.Usuario
|
var user models_seguridad.Usuario
|
||||||
if err := r.db.Preload("Grupos").Where("email = ?", email).First(&user).Error; err != nil {
|
query := r.db.Preload("Grupos")
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Preload("Grupos", "empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.Where("email = ?", email).First(&user).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &user, nil
|
return &user, nil
|
||||||
@@ -141,7 +262,16 @@ func (r *repositorioUsuario) ObtenerPorEmailConGrupos(email string) (*models_seg
|
|||||||
|
|
||||||
func (r *repositorioUsuario) ObtenerGruposPorUsuarioID(usuarioID uint) ([]models_seguridad.Grupo, error) {
|
func (r *repositorioUsuario) ObtenerGruposPorUsuarioID(usuarioID uint) ([]models_seguridad.Grupo, error) {
|
||||||
var grupos []models_seguridad.Grupo
|
var grupos []models_seguridad.Grupo
|
||||||
if err := r.db.Preload("Permisos").Model(&models_seguridad.Usuario{ID: usuarioID}).Association("Grupos").Find(&grupos); err != nil {
|
query := r.db.Table("groupos").
|
||||||
|
Select("groupos.*").
|
||||||
|
Joins("JOIN usuarios_grupos ug ON ug.grupo_id = groupos.id").
|
||||||
|
Where("ug.usuario_id = ?", usuarioID).
|
||||||
|
Where("groupos.deleted_at IS NULL").
|
||||||
|
Preload("Permisos")
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("groupos.empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.Find(&grupos).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return grupos, nil
|
return grupos, nil
|
||||||
@@ -150,28 +280,55 @@ func (r *repositorioUsuario) ObtenerGruposPorUsuarioID(usuarioID uint) ([]models
|
|||||||
func (r *repositorioUsuario) AgregarGrupoAUsuario(usuarioID, grupoID uint) error {
|
func (r *repositorioUsuario) AgregarGrupoAUsuario(usuarioID, grupoID uint) error {
|
||||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
var usu models_seguridad.Usuario
|
var usu models_seguridad.Usuario
|
||||||
if err := tx.Find(&usu, usuarioID).Error; err != nil {
|
if err := tx.First(&usu, usuarioID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return tx.Model(&models_seguridad.Usuario{ID: usuarioID}).Association("Grupos").Append(&models_seguridad.Grupo{ID: grupoID})
|
|
||||||
|
miembro, err := r.EsMiembro(usuarioID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !miembro {
|
||||||
|
return errors.New("el usuario no pertenece a la empresa")
|
||||||
|
}
|
||||||
|
|
||||||
|
var grupo models_seguridad.Grupo
|
||||||
|
query := tx.Where("id = ?", grupoID)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.First(&grupo).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Model(&models_seguridad.Usuario{ID: usuarioID}).Association("Grupos").Append(&grupo)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioUsuario) QuitarGrupoDeUsuario(usuarioID, grupoID uint) error {
|
func (r *repositorioUsuario) QuitarGrupoDeUsuario(usuarioID, grupoID uint) error {
|
||||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
var usu models_seguridad.Usuario
|
var usu models_seguridad.Usuario
|
||||||
if err := tx.Find(&usu, usuarioID).Error; err != nil {
|
if err := tx.First(&usu, usuarioID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if grupoID == 1 {
|
var grupo models_seguridad.Grupo
|
||||||
|
query := tx.Where("id = ?", grupoID)
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
query = query.Where("empresa_id = ?", r.empresaID)
|
||||||
|
}
|
||||||
|
if err := query.First(&grupo).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if grupo.Nombre == "Admin" {
|
||||||
cantidadAdmins := tx.Model(&models_seguridad.Grupo{ID: grupoID}).Association("Usuarios").Count()
|
cantidadAdmins := tx.Model(&models_seguridad.Grupo{ID: grupoID}).Association("Usuarios").Count()
|
||||||
if cantidadAdmins <= 1 {
|
if cantidadAdmins <= 1 {
|
||||||
return errors.New("No se puede eliminar al ultimo administrador")
|
return errors.New("No se puede eliminar al ultimo administrador")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return tx.Model(&models_seguridad.Usuario{ID: usuarioID}).Association("Grupos").Delete(&models_seguridad.Grupo{ID: grupoID})
|
return tx.Model(&models_seguridad.Usuario{ID: usuarioID}).Association("Grupos").Delete(&grupo)
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
+15
-2
@@ -20,11 +20,18 @@ func main() {
|
|||||||
log.Fatalf("failed to connect to database: %v", err)
|
log.Fatalf("failed to connect to database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := config.MigrarAlmacen(); err != nil {
|
||||||
|
log.Fatalf("failed to migrate almacen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
if err := config.DB.AutoMigrate(
|
if err := config.DB.AutoMigrate(
|
||||||
|
&models_seguridad.Empresa{},
|
||||||
&models_seguridad.Usuario{},
|
&models_seguridad.Usuario{},
|
||||||
&models_seguridad.Permiso{},
|
&models_seguridad.Permiso{},
|
||||||
&models_seguridad.Grupo{},
|
&models_seguridad.Grupo{},
|
||||||
// &models_seguridad.Empresa{},
|
&models_seguridad.EmpresaUsuario{},
|
||||||
|
&models_seguridad.PlataformaAdmin{},
|
||||||
|
&models_seguridad.InvitacionEmpresa{},
|
||||||
&models.Almacen{},
|
&models.Almacen{},
|
||||||
&models.Marca{},
|
&models.Marca{},
|
||||||
&models.Repuesto{},
|
&models.Repuesto{},
|
||||||
@@ -50,14 +57,20 @@ func main() {
|
|||||||
log.Fatalf("failed to migrate database: %v", err)
|
log.Fatalf("failed to migrate database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := config.MigrarMultitenant(); err != nil {
|
||||||
|
log.Fatalf("failed to migrate multitenant data: %v", err)
|
||||||
|
}
|
||||||
|
config.InitPermisos()
|
||||||
|
|
||||||
fmt.Println("Database connected and migrated successfully")
|
fmt.Println("Database connected and migrated successfully")
|
||||||
|
|
||||||
repositorios.InicializarRepositorios(config.DB)
|
repositorios.InicializarRepositorios(config.DB)
|
||||||
config.InitPermisos()
|
|
||||||
|
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
|
|
||||||
routes.AuthRoute(r)
|
routes.AuthRoute(r)
|
||||||
|
routes.EmpresaRoute(r)
|
||||||
|
routes.PlataformaRoute(r)
|
||||||
routes.PermisoRoute(r)
|
routes.PermisoRoute(r)
|
||||||
routes.GroupRoute(r)
|
routes.GroupRoute(r)
|
||||||
routes.UserRoute(r)
|
routes.UserRoute(r)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package routes
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"repuestera_back/controllers/auth"
|
"repuestera_back/controllers/auth"
|
||||||
|
"repuestera_back/controllers/empresa"
|
||||||
"repuestera_back/middleware"
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -13,7 +14,25 @@ func AuthRoute(r *gin.Engine) {
|
|||||||
authGroup.POST("/login", auth.Login)
|
authGroup.POST("/login", auth.Login)
|
||||||
authGroup.POST("/register", auth.Register)
|
authGroup.POST("/register", auth.Register)
|
||||||
authGroup.POST("/refresh", auth.Refresh)
|
authGroup.POST("/refresh", auth.Refresh)
|
||||||
authGroup.GET("/me", middleware.AuthMiddleware(), auth.Me)
|
|
||||||
authGroup.POST("/cambiar-contraseña", middleware.AuthMiddleware(), auth.CambiarContraseña)
|
authGroup.GET("/invitaciones/:token", auth.ObtenerInvitacion)
|
||||||
|
authGroup.POST("/invitaciones/:token/aceptar", auth.AceptarInvitacion)
|
||||||
|
}
|
||||||
|
|
||||||
|
session := authGroup.Group("")
|
||||||
|
session.Use(middleware.SesionMiddleware())
|
||||||
|
{
|
||||||
|
session.GET("/me", auth.Me)
|
||||||
|
session.GET("/empresas", auth.ObtenerMisEmpresas)
|
||||||
|
session.POST("/empresa/cambiar", auth.CambiarEmpresa)
|
||||||
|
session.POST("/cambiar-contraseña", auth.CambiarContraseña)
|
||||||
|
session.POST("/cambiar-contrasena", auth.CambiarContraseña)
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaActual := r.Group("/empresa")
|
||||||
|
empresaActual.Use(middleware.AuthMiddleware())
|
||||||
|
{
|
||||||
|
empresaActual.GET("", auth.ObtenerEmpresaActual)
|
||||||
|
empresaActual.PUT("", middleware.AdminEmpresaMiddleware(), empresa.ActualizarEmpresa)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repuestera_back/controllers/empresa"
|
||||||
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EmpresaRoute(r *gin.Engine) {
|
||||||
|
miembros := r.Group("/empresa/miembros")
|
||||||
|
miembros.Use(middleware.AuthMiddleware(), middleware.AdminEmpresaMiddleware())
|
||||||
|
{
|
||||||
|
miembros.GET("", empresa.ObtenerMiembros)
|
||||||
|
miembros.GET("/:id", empresa.ObtenerMiembro)
|
||||||
|
miembros.POST("", empresa.CrearMiembro)
|
||||||
|
miembros.PUT("/:id", empresa.ActualizarMiembro)
|
||||||
|
miembros.DELETE("/:id", empresa.EliminarMiembro)
|
||||||
|
}
|
||||||
|
|
||||||
|
invitaciones := r.Group("/empresa/invitaciones")
|
||||||
|
invitaciones.Use(middleware.AuthMiddleware(), middleware.AdminEmpresaMiddleware())
|
||||||
|
{
|
||||||
|
invitaciones.GET("", empresa.ListarInvitaciones)
|
||||||
|
invitaciones.POST("", empresa.CrearInvitacion)
|
||||||
|
invitaciones.DELETE("/:id", empresa.EliminarInvitacion)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
|
|
||||||
func MarcaRoute(r *gin.Engine) {
|
func MarcaRoute(r *gin.Engine) {
|
||||||
marcaGrupo := r.Group("/marcas")
|
marcaGrupo := r.Group("/marcas")
|
||||||
marcaGrupo.Use(middleware.AuthMiddleware(5))
|
marcaGrupo.Use(middleware.AuthMiddleware(6))
|
||||||
{
|
{
|
||||||
marcaGrupo.GET("/", marca.ObtenerMarcas)
|
marcaGrupo.GET("/", marca.ObtenerMarcas)
|
||||||
// marcaGrupo.GET("/:id", repuestos.ObtenerRepuesto)
|
// marcaGrupo.GET("/:id", repuestos.ObtenerRepuesto)
|
||||||
|
|||||||
@@ -8,18 +8,20 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func PermisoRoute(r *gin.Engine) {
|
func PermisoRoute(r *gin.Engine) {
|
||||||
permGroup := r.Group("/permisos")
|
// Leer el catálogo global es necesario dentro de la empresa para asignar
|
||||||
permGroup.Use(middleware.AuthMiddleware(1))
|
// permisos a grupos. Editarlo queda reservado a plataforma.
|
||||||
|
lectura := r.Group("/permisos")
|
||||||
|
lectura.Use(middleware.AuthMiddleware())
|
||||||
{
|
{
|
||||||
permGroup.POST("", permiso.CrearPermiso)
|
lectura.GET("", permiso.ObtenerPermisos)
|
||||||
permGroup.PUT("/:id", permiso.ActualizarPermiso)
|
lectura.GET("/usuario/:userId", middleware.AuthMiddleware(3, 7), permiso.ObtenerPermisosUsuario)
|
||||||
permGroup.DELETE("/:id", permiso.EliminarPermiso)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
permGroup2 := r.Group("/permisos")
|
escritura := r.Group("/permisos")
|
||||||
permGroup2.Use(middleware.AuthMiddleware(1, 3))
|
escritura.Use(middleware.PlataformaMiddleware())
|
||||||
{
|
{
|
||||||
permGroup2.GET("", permiso.ObtenerPermisos)
|
escritura.POST("", permiso.CrearPermiso)
|
||||||
|
escritura.PUT("/:id", permiso.ActualizarPermiso)
|
||||||
|
escritura.DELETE("/:id", permiso.EliminarPermiso)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repuestera_back/controllers/plataforma"
|
||||||
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func PlataformaRoute(r *gin.Engine) {
|
||||||
|
grupo := r.Group("/plataforma")
|
||||||
|
grupo.Use(middleware.PlataformaMiddleware())
|
||||||
|
{
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
package routes
|
package routes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"repuestera_back/controllers/empresa"
|
||||||
grupo "repuestera_back/controllers/grupos"
|
grupo "repuestera_back/controllers/grupos"
|
||||||
"repuestera_back/controllers/usuarios"
|
|
||||||
"repuestera_back/middleware"
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -10,18 +10,21 @@ import (
|
|||||||
|
|
||||||
func UserRoute(r *gin.Engine) {
|
func UserRoute(r *gin.Engine) {
|
||||||
userGroup := r.Group("/usuarios")
|
userGroup := r.Group("/usuarios")
|
||||||
userGroup.Use(middleware.AuthMiddleware(3))
|
userGroup.Use(middleware.AuthMiddleware(3, 7), middleware.AdminEmpresaMiddleware())
|
||||||
{
|
{
|
||||||
userGroup.GET("", usuarios.ObtenerUsuarios)
|
userGroup.GET("", empresa.ObtenerMiembros)
|
||||||
userGroup.GET("/:id", usuarios.ObtenerUsuario)
|
userGroup.GET("/:id", empresa.ObtenerMiembro)
|
||||||
userGroup.POST("", usuarios.CrearUsuario)
|
userGroup.POST("", empresa.CrearMiembro)
|
||||||
userGroup.PUT("/:id", usuarios.ActualizarUsuario)
|
userGroup.PUT("/:id", empresa.ActualizarMiembro)
|
||||||
userGroup.DELETE("/:id", usuarios.EliminarUsuario)
|
userGroup.DELETE("/:id", empresa.EliminarMiembro)
|
||||||
|
|
||||||
userGroup.GET("/:id/grupos", grupo.ObtenerGruposDeUsuario)
|
userGroup.GET("/:id/grupos", grupo.ObtenerGruposDeUsuario)
|
||||||
userGroup.PUT("/grupos/añadir", grupo.AgregarGrupoAUsuario)
|
userGroup.PUT("/grupos/añadir", grupo.AgregarGrupoAUsuario)
|
||||||
userGroup.PUT("/grupos/quitar", grupo.QuitarGrupoAUsuario)
|
userGroup.PUT("/grupos/quitar", grupo.QuitarGrupoAUsuario)
|
||||||
|
userGroup.PUT("/grupos/anadir", grupo.AgregarGrupoAUsuario)
|
||||||
|
userGroup.PUT("/grupos/quitar-grupo", grupo.QuitarGrupoAUsuario)
|
||||||
}
|
}
|
||||||
|
|
||||||
userSelfGroup := r.Group("/usuarios")
|
userSelfGroup := r.Group("/usuarios")
|
||||||
userSelfGroup.Use(middleware.AuthMiddleware())
|
userSelfGroup.Use(middleware.AuthMiddleware())
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/jwtutils"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EnviarEmailInvitacion intenta notificar la invitación usando el servicio
|
||||||
|
// comms. Un fallo de email no invalida la invitación: el link se devuelve al
|
||||||
|
// administrador para que pueda compartirlo.
|
||||||
|
func EnviarEmailInvitacion(destino, empresa, rol, link string, creadorID uint) bool {
|
||||||
|
base := strings.TrimRight(os.Getenv("COMMS_URL"), "/")
|
||||||
|
if base == "" {
|
||||||
|
base = "http://comms:8088"
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := jwtutils.GenerarToken(
|
||||||
|
creadorID, 0, "", true, "", "repuestera", jwtutils.TokenTypeAccess, nil, 5*time.Minute,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
descripcion := fmt.Sprintf(
|
||||||
|
"<p>Fuiste invitado a <strong>%s</strong> con el rol <strong>%s</strong>.</p>"+
|
||||||
|
"<p><a href=\"%s\">Aceptar invitación</a></p>"+
|
||||||
|
"<p>Si el enlace no funciona, copiá esta dirección: %s</p>",
|
||||||
|
empresa, rol, link, link,
|
||||||
|
)
|
||||||
|
|
||||||
|
cuerpo, _ := json.Marshal(map[string]any{
|
||||||
|
"titulo": "Invitación a " + empresa,
|
||||||
|
"descripcion": descripcion,
|
||||||
|
"items": []string{},
|
||||||
|
"to": []string{destino},
|
||||||
|
})
|
||||||
|
|
||||||
|
cliente := &http.Client{Timeout: 5 * time.Second}
|
||||||
|
req, err := http.NewRequest(http.MethodPost, base+"/email", bytes.NewReader(cuerpo))
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
|
||||||
|
resp, err := cliente.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
return resp.StatusCode >= 200 && resp.StatusCode < 300
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GenerarPasswordTemporal devuelve una clave aleatoria de 18 caracteres.
|
||||||
|
func GenerarPasswordTemporal() (string, error) {
|
||||||
|
bytes := make([]byte, 9)
|
||||||
|
if _, err := rand.Read(bytes); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(bytes), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/dto"
|
||||||
|
"repuestera_back/jwtutils"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
AccessTokenDuration = 15 * time.Minute
|
||||||
|
RefreshTokenDuration = 24 * time.Hour
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUsuarioInactivo = errors.New("el usuario está deshabilitado")
|
||||||
|
ErrSinEmpresas = errors.New("el usuario no pertenece a ninguna empresa activa")
|
||||||
|
ErrSinAcceso = errors.New("no tenés acceso a esta empresa")
|
||||||
|
ErrEmpresaInactiva = errors.New("la empresa está deshabilitada")
|
||||||
|
)
|
||||||
|
|
||||||
|
// ConstruirSesion arma la respuesta de login/refresh con los tokens y el
|
||||||
|
// contexto de la empresa activa.
|
||||||
|
func ConstruirSesion(usuarioID, empresaID uint) (*dto.AuthResponse, error) {
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorID(usuarioID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !usuario.Activo {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
empresa, err = repo.Empresa.ObtenerPorID(empresaID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrSinAcceso
|
||||||
|
}
|
||||||
|
if !empresa.Activa {
|
||||||
|
return nil, ErrEmpresaInactiva
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
permisos,
|
||||||
|
AccessTokenDuration,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshToken, err := jwtutils.GenerarToken(
|
||||||
|
usuario.ID,
|
||||||
|
empresaID,
|
||||||
|
string(empresaRol),
|
||||||
|
esPlataformaAdmin,
|
||||||
|
usuario.Email,
|
||||||
|
usuario.Name,
|
||||||
|
jwtutils.TokenTypeRefresh,
|
||||||
|
permisos,
|
||||||
|
RefreshTokenDuration,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
empresas, err := ListarEmpresasDeUsuario(usuarioID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &dto.AuthResponse{
|
||||||
|
AccessToken: accessToken,
|
||||||
|
RefreshToken: refreshToken,
|
||||||
|
TokenType: "Bearer",
|
||||||
|
ExpiresIn: int(AccessTokenDuration.Seconds()),
|
||||||
|
Permissions: permisos,
|
||||||
|
Empresa: resumenEmpresa,
|
||||||
|
Empresas: empresas,
|
||||||
|
EmpresaRol: string(empresaRol),
|
||||||
|
EsPlataformaAdmin: esPlataformaAdmin,
|
||||||
|
Usuario: dto.UsuarioResumen{
|
||||||
|
ID: usuario.ID,
|
||||||
|
Email: usuario.Email,
|
||||||
|
Name: usuario.Name,
|
||||||
|
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 {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
permisos := utils.PermisosDeUsuario(usuario)
|
||||||
|
if rol == models_seguridad.RolOwner {
|
||||||
|
permisos = anexarUnicos(permisos, models_seguridad.PermisosDeEmpresa())
|
||||||
|
}
|
||||||
|
return permisos, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListarEmpresasDeUsuario devuelve las empresas activas donde el usuario es
|
||||||
|
// miembro, junto con su rol.
|
||||||
|
func ListarEmpresasDeUsuario(usuarioID uint) ([]dto.EmpresaResumen, error) {
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
empresas, err := repo.Empresa.ListarDeUsuario(usuarioID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
resumenes := make([]dto.EmpresaResumen, 0, len(empresas))
|
||||||
|
for _, empresa := range empresas {
|
||||||
|
membresia, err := repo.Empresa.Membresia(empresa.ID, usuarioID)
|
||||||
|
if err != nil || !membresia.Activo {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
resumenes = append(resumenes, dto.EmpresaResumen{
|
||||||
|
ID: empresa.ID,
|
||||||
|
Nombre: empresa.Nombre,
|
||||||
|
Slug: empresa.Slug,
|
||||||
|
Activa: empresa.Activa,
|
||||||
|
Rol: string(membresia.Rol),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return resumenes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func EmpresaDeUsuario(usuarioID, empresaID uint) (*models_seguridad.Empresa, models_seguridad.RolEmpresa, error) {
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
membresia, err := repo.Empresa.Membresia(empresaID, usuarioID)
|
||||||
|
if err != nil || !membresia.Activo {
|
||||||
|
return nil, "", ErrSinAcceso
|
||||||
|
}
|
||||||
|
empresa, err := repo.Empresa.ObtenerPorID(empresaID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", ErrSinAcceso
|
||||||
|
}
|
||||||
|
if !empresa.Activa {
|
||||||
|
return nil, "", ErrEmpresaInactiva
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
vistos[id] = true
|
||||||
|
}
|
||||||
|
for _, id := range extras {
|
||||||
|
if !vistos[id] {
|
||||||
|
base = append(base, id)
|
||||||
|
vistos[id] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(base, func(i, j int) bool { return base[i] < base[j] })
|
||||||
|
return base
|
||||||
|
}
|
||||||
@@ -8,8 +8,6 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
const ContextPermissionsKey = "permissions"
|
|
||||||
|
|
||||||
// PermisosDeUsuario aplana la jerarquia completa de grupos y subgrupos en una
|
// PermisosDeUsuario aplana la jerarquia completa de grupos y subgrupos en una
|
||||||
// lista de IDs de permisos sin duplicados.
|
// lista de IDs de permisos sin duplicados.
|
||||||
func PermisosDeUsuario(usuario *models_seguridad.Usuario) []uint {
|
func PermisosDeUsuario(usuario *models_seguridad.Usuario) []uint {
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ContextPermissionsKey = "permissions"
|
||||||
|
ContextEmpresaIDKey = "empresaID"
|
||||||
|
ContextEmpresaRolKey = "empresaRol"
|
||||||
|
ContextPlataformaAdmin = "esPlataformaAdmin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EmpresaID devuelve la empresa activa que dejo el middleware de auth.
|
||||||
|
func EmpresaID(c *gin.Context) uint {
|
||||||
|
value, ok := c.Get(ContextEmpresaIDKey)
|
||||||
|
if !ok {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
id, _ := value.(uint)
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetEmpresaID guarda la empresa activa en el contexto de Gin.
|
||||||
|
func SetEmpresaID(c *gin.Context, id uint) {
|
||||||
|
c.Set(ContextEmpresaIDKey, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EmpresaRol devuelve el rol del usuario dentro de la empresa activa.
|
||||||
|
func EmpresaRol(c *gin.Context) string {
|
||||||
|
value, ok := c.Get(ContextEmpresaRolKey)
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -3,12 +3,11 @@ import {
|
|||||||
getAuthTokens,
|
getAuthTokens,
|
||||||
getTokenExpiry,
|
getTokenExpiry,
|
||||||
notifyAuthChange,
|
notifyAuthChange,
|
||||||
removeAuthTokens,
|
|
||||||
removeToken,
|
|
||||||
setAuthTokens,
|
setAuthTokens,
|
||||||
setToken
|
setToken
|
||||||
} from '$lib/hooks/token';
|
} from '$lib/hooks/token';
|
||||||
import { getCurrentUser, removeCurrentUser, setCurrentUser } from '$lib/hooks/user';
|
import { getCurrentUser, setCurrentUser } from '$lib/hooks/user';
|
||||||
|
import { aplicarSesion, cerrarSesion } from '$lib/hooks/session';
|
||||||
|
|
||||||
export class TokenRefresher {
|
export class TokenRefresher {
|
||||||
private timer: ReturnType<typeof setInterval> | null = null;
|
private timer: ReturnType<typeof setInterval> | null = null;
|
||||||
@@ -68,26 +67,10 @@ export class TokenRefresher {
|
|||||||
if (!res.ok) throw new Error('Refresh failed');
|
if (!res.ok) throw new Error('Refresh failed');
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setAuthTokens({
|
aplicarSesion(data);
|
||||||
access_token: data.access_token,
|
|
||||||
refresh_token: data.refresh_token,
|
|
||||||
expires_in: data.expires_in,
|
|
||||||
token_type: data.token_type,
|
|
||||||
permissions: data.permissions
|
|
||||||
});
|
|
||||||
setToken(data.access_token);
|
|
||||||
|
|
||||||
const currentUser = getCurrentUser();
|
|
||||||
if (currentUser) {
|
|
||||||
setCurrentUser({ ...currentUser, permissions: data.permissions ?? [] });
|
|
||||||
}
|
|
||||||
|
|
||||||
this.schedule();
|
this.schedule();
|
||||||
} catch {
|
} catch {
|
||||||
removeAuthTokens();
|
cerrarSesion();
|
||||||
removeToken();
|
|
||||||
removeCurrentUser();
|
|
||||||
notifyAuthChange();
|
|
||||||
this.stop();
|
this.stop();
|
||||||
this.onExpired();
|
this.onExpired();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { goto } from '$app/navigation';
|
||||||
|
import { API_URL } from './env';
|
||||||
|
import { cerrarSesion } from './hooks/session';
|
||||||
|
import { getToken } from './hooks/token';
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
status: number;
|
||||||
|
|
||||||
|
constructor(status: number, message: string) {
|
||||||
|
super(message);
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ApiOptions = Omit<RequestInit, 'body'> & {
|
||||||
|
body?: unknown;
|
||||||
|
auth?: boolean;
|
||||||
|
rawBody?: BodyInit | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function apiFetch<T>(path: string, options: ApiOptions = {}): Promise<T> {
|
||||||
|
const { auth = true, body, rawBody, headers, ...rest } = options;
|
||||||
|
const finalHeaders = new Headers(headers);
|
||||||
|
|
||||||
|
if (auth) {
|
||||||
|
const token = getToken();
|
||||||
|
if (token) finalHeaders.set('Authorization', `Bearer ${token}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let finalBody: BodyInit | null | undefined = rawBody;
|
||||||
|
if (body !== undefined) {
|
||||||
|
finalHeaders.set('Content-Type', 'application/json');
|
||||||
|
finalBody = JSON.stringify(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(`${API_URL}${path}`, {
|
||||||
|
...rest,
|
||||||
|
headers: finalHeaders,
|
||||||
|
body: finalBody
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
cerrarSesion();
|
||||||
|
void goto('/login');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const data = await response.json().catch(() => ({}));
|
||||||
|
throw new ApiError(response.status, data.error || data.message || 'Error en la petición');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 204) return undefined as T;
|
||||||
|
return (await response.json()) as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mensajeError(error: unknown): string {
|
||||||
|
if (error instanceof Error) return error.message;
|
||||||
|
return 'Error desconocido';
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
import UserMenu from './UserMenu.svelte';
|
import UserMenu from './UserMenu.svelte';
|
||||||
import type { GruposYPermisosResponse, Usuario } from '../../types';
|
import type { GruposYPermisosResponse, Usuario } from '../../types';
|
||||||
import { getCurrentUser } from '$lib/hooks/user';
|
import { getCurrentUser } from '$lib/hooks/user';
|
||||||
import { ObtenerGruposDeUsuario } from '$lib/hooks/ObtenerGruposDeUsuario';
|
import { ObtenerGruposDeUsuario } from '$lib/hooks/gruposPermisosUsuario';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
|
|
||||||
interface Prop {
|
interface Prop {
|
||||||
@@ -19,19 +19,22 @@
|
|||||||
|
|
||||||
let { usuario, grupos }: Prop = $props();
|
let { usuario, grupos }: Prop = $props();
|
||||||
|
|
||||||
|
const nombreEmpresa = $derived(usuario?.empresa?.nombre ?? 'Repuestera');
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
if (typeof usuario === 'undefined') {
|
if (typeof usuario === 'undefined') {
|
||||||
usuario = getCurrentUser() ?? undefined;
|
usuario = getCurrentUser() ?? undefined;
|
||||||
}
|
}
|
||||||
if (typeof grupos === 'undefined') {
|
if (typeof grupos === 'undefined') {
|
||||||
grupos = usuario
|
grupos =
|
||||||
|
usuario && usuario.empresa
|
||||||
? ObtenerGruposDeUsuario(usuario)
|
? ObtenerGruposDeUsuario(usuario)
|
||||||
: Promise.resolve({ email: '', groups: [] });
|
: Promise.resolve({ email: '', groups: [] });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<CarbonHeader companyName="Repuestera" href="/menu">
|
<CarbonHeader companyName={nombreEmpresa} href="/menu">
|
||||||
<HeaderNav>
|
<HeaderNav>
|
||||||
{#if !usuario}
|
{#if !usuario}
|
||||||
<HeaderNavItem text="Inicio" href="/" />
|
<HeaderNavItem text="Inicio" href="/" />
|
||||||
|
|||||||
@@ -1,19 +1,40 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Logout from 'carbon-icons-svelte/lib/Logout.svelte';
|
import Logout from 'carbon-icons-svelte/lib/Logout.svelte';
|
||||||
import ChevronDown from 'carbon-icons-svelte/lib/ChevronDown.svelte';
|
import ChevronDown from 'carbon-icons-svelte/lib/ChevronDown.svelte';
|
||||||
import { getCurrentUser, removeCurrentUser } from '$lib/hooks/user';
|
import Building from 'carbon-icons-svelte/lib/Building.svelte';
|
||||||
import { notifyAuthChange, removeAuthTokens, removeToken } from '$lib/hooks/token';
|
import UserAdmin from 'carbon-icons-svelte/lib/UserAdmin.svelte';
|
||||||
import { goto } from '$app/navigation';
|
import Password from 'carbon-icons-svelte/lib/Password.svelte';
|
||||||
|
import Checkmark from 'carbon-icons-svelte/lib/Checkmark.svelte';
|
||||||
|
import { getCurrentUser } from '$lib/hooks/user';
|
||||||
|
import { cerrarSesion } from '$lib/hooks/session';
|
||||||
|
import { AUTH_CHANGE_EVENT } from '$lib/hooks/token';
|
||||||
|
import { cambiarEmpresa } from '$lib/hooks/tenant';
|
||||||
|
import { goto, invalidateAll } from '$app/navigation';
|
||||||
|
|
||||||
let user = $state(getCurrentUser());
|
let user = $state(getCurrentUser());
|
||||||
let dropdownOpen = $state(false);
|
let dropdownOpen = $state(false);
|
||||||
|
let cambiando = $state(false);
|
||||||
|
let error = $state('');
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const sync = () => {
|
||||||
|
user = getCurrentUser();
|
||||||
|
};
|
||||||
|
window.addEventListener(AUTH_CHANGE_EVENT, sync);
|
||||||
|
return () => window.removeEventListener(AUTH_CHANGE_EVENT, sync);
|
||||||
|
});
|
||||||
|
|
||||||
|
const empresas = $derived(user?.empresas ?? []);
|
||||||
|
const empresaActual = $derived(user?.empresa ?? null);
|
||||||
|
const esAdminEmpresa = $derived(
|
||||||
|
user?.empresa_rol === 'OWNER' ||
|
||||||
|
user?.empresa_rol === 'ADMIN' ||
|
||||||
|
(user?.permissions ?? []).some((p) => p === 3 || p === 7)
|
||||||
|
);
|
||||||
|
|
||||||
function handleLogout() {
|
function handleLogout() {
|
||||||
removeAuthTokens();
|
cerrarSesion();
|
||||||
removeToken();
|
void goto('/login');
|
||||||
removeCurrentUser();
|
|
||||||
notifyAuthChange();
|
|
||||||
goto('/login');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleDropdown() {
|
function toggleDropdown() {
|
||||||
@@ -23,6 +44,25 @@
|
|||||||
function closeDropdown() {
|
function closeDropdown() {
|
||||||
dropdownOpen = false;
|
dropdownOpen = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function seleccionarEmpresa(id: number) {
|
||||||
|
if (!id || id === empresaActual?.id) {
|
||||||
|
dropdownOpen = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
cambiando = true;
|
||||||
|
error = '';
|
||||||
|
try {
|
||||||
|
await cambiarEmpresa(id);
|
||||||
|
await goto('/menu');
|
||||||
|
await invalidateAll();
|
||||||
|
} catch (e) {
|
||||||
|
error = e instanceof Error ? e.message : 'No se pudo cambiar de empresa';
|
||||||
|
} finally {
|
||||||
|
cambiando = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if user}
|
{#if user}
|
||||||
@@ -38,13 +78,86 @@
|
|||||||
>{(user?.name?.[0] || user?.email?.[0])?.toUpperCase()}</span
|
>{(user?.name?.[0] || user?.email?.[0])?.toUpperCase()}</span
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
|
{#if empresaActual}
|
||||||
|
<span class="hidden max-w-40 truncate text-xs sm:inline">{empresaActual.nombre}</span>
|
||||||
|
{/if}
|
||||||
<ChevronDown size={16} />
|
<ChevronDown size={16} />
|
||||||
</button>
|
</button>
|
||||||
{#if dropdownOpen}
|
{#if dropdownOpen}
|
||||||
<div
|
<div
|
||||||
class="bg-grey-800 absolute top-full right-0 z-50 mt-1 overflow-hidden border shadow-lg"
|
class="bg-grey-800 absolute top-full right-0 z-50 mt-1 w-64 overflow-hidden border shadow-lg"
|
||||||
role="menu"
|
role="menu"
|
||||||
>
|
>
|
||||||
|
<div class="border-b border-gray-600 px-4 py-3">
|
||||||
|
<p class="truncate text-sm font-semibold text-gray-100">{user.name}</p>
|
||||||
|
<p class="truncate text-xs text-gray-400">{user.email}</p>
|
||||||
|
{#if empresaActual}
|
||||||
|
<p class="mt-1 text-xs text-gray-300">
|
||||||
|
{empresaActual.nombre}
|
||||||
|
{#if user.empresa_rol}
|
||||||
|
<span class="text-gray-500">· {user.empresa_rol}</span>
|
||||||
|
{/if}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if empresas.length > 1}
|
||||||
|
<div class="border-b border-gray-600 py-2">
|
||||||
|
<p class="px-4 pb-1 text-[0.65rem] tracking-wider text-gray-400 uppercase">
|
||||||
|
Cambiar empresa
|
||||||
|
</p>
|
||||||
|
{#each empresas as empresa (empresa.id)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex w-full items-center justify-between gap-2 px-4 py-2 text-left text-sm text-gray-300 transition-colors hover:bg-gray-700 disabled:opacity-50"
|
||||||
|
role="menuitem"
|
||||||
|
disabled={cambiando || empresa.id === empresaActual?.id}
|
||||||
|
onclick={() => seleccionarEmpresa(empresa.id)}
|
||||||
|
>
|
||||||
|
<span class="truncate">{empresa.nombre}</span>
|
||||||
|
{#if empresa.id === empresaActual?.id}
|
||||||
|
<Checkmark size={16} />
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
{#if error}
|
||||||
|
<p class="px-4 pt-1 text-xs text-red-400">{error}</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="py-1">
|
||||||
|
{#if esAdminEmpresa}
|
||||||
|
<a
|
||||||
|
href="/empresa"
|
||||||
|
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"
|
||||||
|
role="menuitem"
|
||||||
|
onclick={closeDropdown}
|
||||||
|
>
|
||||||
|
<Building size={16} />
|
||||||
|
Mi empresa
|
||||||
|
</a>
|
||||||
|
{/if}
|
||||||
|
{#if user.es_plataforma_admin}
|
||||||
|
<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"
|
||||||
|
role="menuitem"
|
||||||
|
onclick={closeDropdown}
|
||||||
|
>
|
||||||
|
<UserAdmin size={16} />
|
||||||
|
Plataforma
|
||||||
|
</a>
|
||||||
|
{/if}
|
||||||
|
<a
|
||||||
|
href="/cambiar-contraseña"
|
||||||
|
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"
|
||||||
|
role="menuitem"
|
||||||
|
onclick={closeDropdown}
|
||||||
|
>
|
||||||
|
<Password size={16} />
|
||||||
|
Cambiar contraseña
|
||||||
|
</a>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex w-full items-center gap-2 px-4 py-2.5 text-sm text-gray-300 transition-colors hover:bg-gray-700"
|
class="flex w-full items-center gap-2 px-4 py-2.5 text-sm text-gray-300 transition-colors hover:bg-gray-700"
|
||||||
@@ -52,9 +165,10 @@
|
|||||||
onclick={handleLogout}
|
onclick={handleLogout}
|
||||||
>
|
>
|
||||||
<Logout size={16} />
|
<Logout size={16} />
|
||||||
Cerrar Sesion
|
Cerrar sesión
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
|
|||||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user