Private
Public Access
174 lines
5.0 KiB
Go
174 lines
5.0 KiB
Go
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
|
|
}
|