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)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func Me(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.Split(authHeader, " ")
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header format"})
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := parts[1]
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return JWTSecret, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
return
|
||||
}
|
||||
|
||||
sub, ok := claims["sub"].(string)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
return
|
||||
}
|
||||
userID, _ := strconv.ParseUint(sub, 10, 32)
|
||||
var user models.Usuario
|
||||
if err := config.DB.First(&user, userID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.MeResponse{
|
||||
ID: user.ID,
|
||||
Email: user.Email,
|
||||
Name: user.Name,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func Refresh(c *gin.Context) {
|
||||
var req dto.RefreshRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := req.RefreshToken
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return JWTSecret, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid refresh token"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
return
|
||||
}
|
||||
|
||||
sub, ok := claims["sub"].(string)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
return
|
||||
}
|
||||
userID, _ := strconv.ParseUint(sub, 10, 32)
|
||||
var user models.Usuario
|
||||
if err := config.DB.First(&user, userID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, err := generarToken(user, 15*time.Minute)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
||||
return
|
||||
}
|
||||
|
||||
newRefreshToken, 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: newRefreshToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: 900,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func Register(c *gin.Context) {
|
||||
var req dto.RegisterRequest
|
||||
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 existing models.Usuario
|
||||
if err := config.DB.Where("LOWER(email) = ?", email).First(&existing).Error; err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "El email ya esta registrado"})
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contrasena"})
|
||||
return
|
||||
}
|
||||
|
||||
user := models.Usuario{
|
||||
Email: email,
|
||||
Password: string(hashedPassword),
|
||||
Name: req.Name,
|
||||
}
|
||||
|
||||
if err := config.DB.Create(&user).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dto.RegisterResponse{
|
||||
ID: user.ID,
|
||||
Email: user.Email,
|
||||
Name: user.Name,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package permission
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerGrupos(c *gin.Context) {
|
||||
var grupos []models.Grupo
|
||||
if err := config.DB.Preload("Permisos").Preload("Grupos").Find(&grupos).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, grupos)
|
||||
}
|
||||
|
||||
func CrearGrupo(c *gin.Context) {
|
||||
var grupo models.Grupo
|
||||
if err := c.ShouldBindJSON(&grupo); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err := config.DB.Create(&grupo).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, grupo)
|
||||
}
|
||||
|
||||
func ActualizarGrupo(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var grupo models.Grupo
|
||||
if err := config.DB.First(&grupo, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||
return
|
||||
}
|
||||
var input models.Grupo
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
config.DB.Model(&grupo).Updates(input)
|
||||
c.JSON(http.StatusOK, grupo)
|
||||
}
|
||||
|
||||
func EliminarGrupo(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if err := config.DB.Delete(&models.Grupo{}, id).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Grupo eliminado"})
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package permission
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AsignarPermisoAGrupo(c *gin.Context) {
|
||||
var req dto.GrupoPermisoRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
grupoID := c.Param("id")
|
||||
var grupo models.Grupo
|
||||
if err := config.DB.First(&grupo, grupoID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var permiso models.Permiso
|
||||
if err := config.DB.First(&permiso, req.PermissionID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Permiso no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
config.DB.Model(&grupo).Association("Permisos").Append(&permiso)
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Permiso asignado al grupo"})
|
||||
}
|
||||
|
||||
func QuitarPermisoAGrupo(c *gin.Context) {
|
||||
var req dto.GrupoPermisoRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
grupoID := c.Param("id")
|
||||
var grupo models.Grupo
|
||||
if err := config.DB.First(&grupo, grupoID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var permiso models.Permiso
|
||||
if err := config.DB.First(&permiso, req.PermissionID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Permiso no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
config.DB.Model(&grupo).Association("Permisos").Delete(&permiso)
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Permiso quitado del grupo"})
|
||||
}
|
||||
|
||||
func AgregarSubGrupo(c *gin.Context) {
|
||||
var req dto.GrupoHijoRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
padreID := c.Param("id")
|
||||
var padre models.Grupo
|
||||
if err := config.DB.First(&padre, padreID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo padre no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var hijo models.Grupo
|
||||
if err := config.DB.First(&hijo, req.ChildGroupID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo hijo no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
config.DB.Model(&padre).Association("Grupos").Append(&hijo)
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Subgrupo agregado"})
|
||||
}
|
||||
|
||||
func QuitarSubGrupo(c *gin.Context) {
|
||||
var req dto.GrupoHijoRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
padreID := c.Param("id")
|
||||
var padre models.Grupo
|
||||
if err := config.DB.First(&padre, padreID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo padre no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var hijo models.Grupo
|
||||
if err := config.DB.First(&hijo, req.ChildGroupID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo hijo no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
config.DB.Model(&padre).Association("Grupos").Delete(&hijo)
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Subgrupo quitado"})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package permission
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerPermisos(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, 1) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para listar permisos"})
|
||||
return
|
||||
}
|
||||
|
||||
var permisos []models.Permiso
|
||||
if err := config.DB.Find(&permisos).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, permisos)
|
||||
}
|
||||
|
||||
func CrearPermiso(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, 2) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para crear permisos"})
|
||||
return
|
||||
}
|
||||
|
||||
var permiso models.Permiso
|
||||
if err := c.ShouldBindJSON(&permiso); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err := config.DB.Create(&permiso).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, permiso)
|
||||
}
|
||||
|
||||
func ActualizarPermiso(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, 3) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para actualizar permisos"})
|
||||
return
|
||||
}
|
||||
|
||||
id := c.Param("id")
|
||||
var permiso models.Permiso
|
||||
if err := config.DB.First(&permiso, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Permiso no encontrado"})
|
||||
return
|
||||
}
|
||||
var input models.Permiso
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
config.DB.Model(&permiso).Updates(input)
|
||||
c.JSON(http.StatusOK, permiso)
|
||||
}
|
||||
|
||||
func EliminarPermiso(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, 4) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para eliminar permisos"})
|
||||
return
|
||||
}
|
||||
|
||||
id := c.Param("id")
|
||||
if err := config.DB.Delete(&models.Permiso{}, id).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Permiso eliminado"})
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package permission
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/jwtutils"
|
||||
"repuestera_back/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func ObtenerPermisosUsuario(c *gin.Context) {
|
||||
userID := c.Param("userId")
|
||||
var usuario models.Usuario
|
||||
if err := config.DB.Preload("Groups.Permissions").Preload("Groups.Groups.Permissions").First(&usuario, userID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
permisoMap := make(map[string]bool)
|
||||
var permisos []string
|
||||
|
||||
for _, grupo := range usuario.Grupos {
|
||||
for _, permiso := range grupo.Permisos {
|
||||
if !permisoMap[permiso.Nombre] {
|
||||
permisoMap[permiso.Nombre] = true
|
||||
permisos = append(permisos, permiso.Nombre)
|
||||
}
|
||||
}
|
||||
for _, grupoHijo := range grupo.Grupos {
|
||||
for _, permiso := range grupoHijo.Permisos {
|
||||
if !permisoMap[permiso.Nombre] {
|
||||
permisoMap[permiso.Nombre] = true
|
||||
permisos = append(permisos, permiso.Nombre)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.PermisosUsuarioResponse{Permissions: permisos})
|
||||
}
|
||||
|
||||
func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
||||
var request struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Formato de solicitud invalido"})
|
||||
return
|
||||
}
|
||||
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: Header Authorization no presente"})
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := ""
|
||||
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
|
||||
tokenString = authHeader[7:]
|
||||
} else {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Formato de token invalido"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := jwtutils.ValidarJWT(tokenString)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token invalido o expirado", "details": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
jwtEmail, ok := claims["email"].(string)
|
||||
if !ok || jwtEmail == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Email no encontrado en el token"})
|
||||
return
|
||||
}
|
||||
|
||||
if jwtEmail != request.Email {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: El email no coincide con el token JWT"})
|
||||
return
|
||||
}
|
||||
|
||||
var usuario models.Usuario
|
||||
if err := config.DB.Preload("Groups.Permissions").Preload("Groups.Groups.Permissions").Where("email = ?", request.Email).First(&usuario).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
grupoPermisoMap := make(map[uint]*dto.GrupoInfo)
|
||||
permisoSet := make(map[string]bool)
|
||||
|
||||
for _, grupo := range usuario.Grupos {
|
||||
if _, ok := grupoPermisoMap[grupo.ID]; !ok {
|
||||
grupoPermisoMap[grupo.ID] = &dto.GrupoInfo{
|
||||
ID: grupo.ID,
|
||||
Name: grupo.Nombre,
|
||||
Permissions: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
for _, permiso := range grupo.Permisos {
|
||||
if !permisoSet[permiso.Nombre] {
|
||||
permisoSet[permiso.Nombre] = true
|
||||
grupoPermisoMap[grupo.ID].Permissions = append(grupoPermisoMap[grupo.ID].Permissions, permiso.Nombre)
|
||||
}
|
||||
}
|
||||
|
||||
for _, subGrupo := range grupo.Grupos {
|
||||
if _, ok := grupoPermisoMap[subGrupo.ID]; !ok {
|
||||
grupoPermisoMap[subGrupo.ID] = &dto.GrupoInfo{
|
||||
ID: subGrupo.ID,
|
||||
Name: subGrupo.Nombre,
|
||||
Permissions: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
for _, permiso := range subGrupo.Permisos {
|
||||
if !permisoSet[permiso.Nombre] {
|
||||
permisoSet[permiso.Nombre] = true
|
||||
grupoPermisoMap[subGrupo.ID].Permissions = append(grupoPermisoMap[subGrupo.ID].Permissions, permiso.Nombre)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
grupos := make([]dto.GrupoInfo, 0, len(grupoPermisoMap))
|
||||
for _, grupo := range grupoPermisoMap {
|
||||
grupos = append(grupos, *grupo)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.GruposYPermisosResponse{
|
||||
UserID: usuario.ID,
|
||||
Email: usuario.Email,
|
||||
Groups: grupos,
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user