Private
Public Access
primeros cambios hechos para tener el multitenant
This commit is contained in:
1 parent
34ad4424f9
commit
4e082e8767
132 files changed
+6202
-762
No files matched your search
@@ -3,6 +3,7 @@ package auth
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
|
||||
@@ -22,7 +23,7 @@ func CambiarContraseña(c *gin.Context) {
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -30,30 +31,47 @@ func CambiarContraseña(c *gin.Context) {
|
||||
authUserIDUint, _ := authUserID.(uint)
|
||||
|
||||
targetID := authUserIDUint
|
||||
if req.UserID != 0 {
|
||||
esPropia := req.UserID == 0 || req.UserID == authUserIDUint
|
||||
if !esPropia {
|
||||
targetID = req.UserID
|
||||
}
|
||||
|
||||
esAdmin := utils.UsuarioTienePermiso(c, 3)
|
||||
|
||||
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)
|
||||
repo := r.ObtenerRepositorios()
|
||||
user, err := repo.Usuario.ObtenerPorID(targetID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "usuario no encontrado"})
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
if !esAdmin {
|
||||
// Cambiar la contraseña propia siempre exige la contraseña actual.
|
||||
if esPropia {
|
||||
if req.OldPassword == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Se requiere la contraseña actual"})
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -64,7 +82,8 @@ func CambiarContraseña(c *gin.Context) {
|
||||
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"})
|
||||
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"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/jwtutils"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
"repuestera_back/services"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type loginRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
EmpresaID uint `json:"empresa_id"`
|
||||
EmpresaSlug string `json:"empresa_slug"`
|
||||
}
|
||||
|
||||
func Login(c *gin.Context) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
var req loginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
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 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail Invalido"})
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail o contraseña inválidos"})
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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 {
|
||||
log.Printf("login: no se pudieron cargar los permisos del usuario %d: %v", user.ID, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "No se pudieron cargar los permisos del usuario"})
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
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 {
|
||||
log.Printf("login: no se pudo generar el access token del usuario %d: %v", user.ID, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
||||
status := http.StatusForbidden
|
||||
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
|
||||
}
|
||||
|
||||
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 {
|
||||
log.Printf("login: 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: refreshToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: 900,
|
||||
Permissions: permisos,
|
||||
})
|
||||
return 0, err
|
||||
}
|
||||
if len(empresas) > 0 {
|
||||
return empresas[0].ID, nil
|
||||
}
|
||||
|
||||
if services.EsPlataformaAdmin(usuarioID) {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, services.ErrSinEmpresas
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"net/http"
|
||||
|
||||
"repuestera_back/dto"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -18,16 +20,93 @@ func Me(c *gin.Context) {
|
||||
|
||||
id, ok := userID.(uint)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "token inválido"})
|
||||
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{
|
||||
ID: id,
|
||||
Email: c.GetString("email"),
|
||||
Name: c.GetString("name"),
|
||||
Permissions: permisos,
|
||||
ID: respuesta.Usuario.ID,
|
||||
Email: respuesta.Usuario.Email,
|
||||
Name: respuesta.Usuario.Name,
|
||||
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 (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/jwtutils"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
"repuestera_back/services"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -24,43 +22,34 @@ func Refresh(c *gin.Context) {
|
||||
|
||||
claims, err := jwtutils.ValidarTokenDeTipo(req.RefreshToken, jwtutils.TokenTypeRefresh)
|
||||
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
|
||||
}
|
||||
|
||||
sub, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "refresh token inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(sub)
|
||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(sub)
|
||||
if err != nil {
|
||||
log.Printf("refresh: no se pudo cargar el usuario %d: %v", sub, err)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "usuario no encontrado"})
|
||||
return
|
||||
}
|
||||
if !user.Activo {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "la cuenta está deshabilitada"})
|
||||
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 {
|
||||
log.Printf("refresh: no se pudo generar el access token del usuario %d: %v", user.ID, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
||||
log.Printf("refresh: no se pudo renovar la sesión del usuario %d: %v", user.ID, err)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
newRefreshToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeRefresh, permisos, 24*time.Hour)
|
||||
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,
|
||||
})
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"repuestera_back/dto"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
@@ -14,9 +15,12 @@ import (
|
||||
|
||||
func Register(c *gin.Context) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=8"`
|
||||
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 {
|
||||
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))
|
||||
repo := r.ObtenerRepositorios()
|
||||
|
||||
if _, err := r.ObtenerRepositorios().Usuario.ObtenerPorEmail(email); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "El email ya esta registrado"})
|
||||
if _, err := repo.Usuario.ObtenerPorEmail(email); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "El email ya está registrado"})
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
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
|
||||
}
|
||||
|
||||
user := models_seguridad.Usuario{
|
||||
Email: email,
|
||||
Password: string(hashedPassword),
|
||||
Name: req.Name,
|
||||
Name: strings.TrimSpace(req.Name),
|
||||
Activo: true,
|
||||
}
|
||||
|
||||
//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 {
|
||||
if err := repo.Usuario.Crear(&user); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dto.RegisterResponse{
|
||||
ID: user.ID,
|
||||
Email: user.Email,
|
||||
Name: user.Name,
|
||||
})
|
||||
nombreEmpresa := strings.TrimSpace(req.EmpresaNombre)
|
||||
if nombreEmpresa == "" {
|
||||
nombreEmpresa = "Empresa de " + 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)
|
||||
}
|
||||
Reference in new issue
Block a user