Private
Public Access
69 lines
1.7 KiB
Go
69 lines
1.7 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"repuestera_back/dto"
|
|
"repuestera_back/jwtutils"
|
|
models_seguridad "repuestera_back/models/seguridad"
|
|
r "repuestera_back/repositorios"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func Login(c *gin.Context) {
|
|
var req dto.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)
|
|
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
|
|
}
|
|
|
|
accessToken, err := generarToken(*user, 15*time.Minute)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
|
return
|
|
}
|
|
|
|
refreshToken, err := generarToken(*user, 24*time.Hour)
|
|
if err != nil {
|
|
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,
|
|
})
|
|
}
|
|
|
|
func generarToken(user models_seguridad.Usuario, duration time.Duration) (string, error) {
|
|
claims := jwt.MapClaims{
|
|
"sub": user.ID,
|
|
"email": user.Email,
|
|
"name": user.Name,
|
|
"exp": time.Now().Add(duration).Unix(),
|
|
"iat": time.Now().Unix(),
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString(jwtutils.JWTSecret)
|
|
}
|