Private
Public Access
JIJO recupere el codigo dsps que de claude nukee mi repo LETS GOOO
This commit is contained in:
1 parent
a35539590a
commit
6c1bc50089
24 files changed
+1260
No files matched your search
@@ -0,0 +1,69 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
var JWTSecret = []byte("supersecretkey123456789")
|
||||
|
||||
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))
|
||||
var user models.Usuario
|
||||
if err := config.DB.Select("id", "email", "name", "password").Where("LOWER(email) = ?", email).First(&user).Error; 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.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(JWTSecret)
|
||||
}
|
||||
Reference in new issue
Block a user