Files
Repuestera/back/controllers/auth/Register.go
T

64 lines
1.6 KiB
Go

package auth
import (
"net/http"
"strings"
"repuestera_back/dto"
models_seguridad "repuestera_back/models/seguridad"
r "repuestera_back/repositorios"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
func Register(c *gin.Context) {
var req dto.RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
email := strings.ToLower(strings.TrimSpace(req.Email))
if _, err := r.ObtenerRepositorios().Usuario.ObtenerPorEmail(email); err == nil {
c.JSON(http.StatusConflict, gin.H{"error": "El email ya esta 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"})
return
}
user := models_seguridad.Usuario{
Email: email,
Password: string(hashedPassword),
Name: req.Name,
}
//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()})
return
}
c.JSON(http.StatusCreated, dto.RegisterResponse{
ID: user.ID,
Email: user.Email,
Name: user.Name,
})
}