Private
Public Access
77 lines
2.0 KiB
Go
77 lines
2.0 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"repuestera_back/dto"
|
|
"repuestera_back/repositories"
|
|
"repuestera_back/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
var usuarioRepo repositories.RepositorioUsuario
|
|
|
|
func InitUsuarioRepository(repo repositories.RepositorioUsuario) {
|
|
usuarioRepo = repo
|
|
}
|
|
|
|
func CambiarContraseña(c *gin.Context) {
|
|
var req dto.CambiarContraseñaRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
if len(req.NewPassword) < 8 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La nueva contraseña debe tener mas de 8 caracteres"})
|
|
return
|
|
}
|
|
|
|
authUserID, _ := c.Get("userID")
|
|
authUserIDUint, _ := authUserID.(uint)
|
|
|
|
targetID := authUserIDUint
|
|
if req.UserID != 0 {
|
|
targetID = req.UserID
|
|
}
|
|
|
|
esAdmin := utils.UsuarioTienePermiso(c, 3)
|
|
|
|
if targetID != authUserIDUint && !esAdmin {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para cambiar la contraseña de otro usuario"})
|
|
return
|
|
}
|
|
|
|
user, err := usuarioRepo.ObtenerPorID(targetID)
|
|
if err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "usuario no encontrado"})
|
|
return
|
|
}
|
|
|
|
if !esAdmin {
|
|
if req.OldPassword == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Se requiere la contraseña actual"})
|
|
return
|
|
}
|
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "contraseña actual incorrecta"})
|
|
return
|
|
}
|
|
}
|
|
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
|
return
|
|
}
|
|
|
|
if err := usuarioRepo.ActualizarContraseña(user.ID, string(hashedPassword)); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al actualizar la contraseña"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "Contraseña actualizada exitosamente"})
|
|
}
|