Private
Public Access
88 lines
2.4 KiB
Go
88 lines
2.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
|
models_seguridad "repuestera_back/models/seguridad"
|
|
r "repuestera_back/repositorios"
|
|
"repuestera_back/services"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func Register(c *gin.Context) {
|
|
var req struct {
|
|
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()})
|
|
return
|
|
}
|
|
|
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
|
repo := r.ObtenerRepositorios()
|
|
|
|
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 contraseña"})
|
|
return
|
|
}
|
|
|
|
user := models_seguridad.Usuario{
|
|
Email: email,
|
|
Password: string(hashedPassword),
|
|
Name: strings.TrimSpace(req.Name),
|
|
Activo: true,
|
|
}
|
|
if err := repo.Usuario.Crear(&user); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
respuesta, err := services.ConstruirSesion(user.ID, empresa.ID)
|
|
if err != nil {
|
|
registro, buildErr := dto_directors.NewRegisterDirector().DesdeUsuario(&user)
|
|
if buildErr != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": buildErr.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, registro)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, respuesta)
|
|
}
|