Private
Public Access
70 lines
2.1 KiB
Go
70 lines
2.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"repuestera_back/dto"
|
|
"repuestera_back/jwtutils"
|
|
r "repuestera_back/repositorios"
|
|
"repuestera_back/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func Login(c *gin.Context) {
|
|
var req struct {
|
|
Email string `json:"email" binding:"required,email"`
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
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)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail Invalido"})
|
|
return
|
|
}
|
|
|
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Contrasena invalida"})
|
|
return
|
|
}
|
|
|
|
usuarioConPermisos, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(user.ID)
|
|
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"})
|
|
return
|
|
}
|
|
permisos := utils.PermisosDeUsuario(usuarioConPermisos)
|
|
|
|
accessToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeAccess, permisos, 15*time.Minute)
|
|
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"})
|
|
return
|
|
}
|
|
|
|
refreshToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeRefresh, permisos, 24*time.Hour)
|
|
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,
|
|
})
|
|
}
|