Private
Public Access
actualizado tema tokens
This commit is contained in:
1 parent
38afdcc742
commit
441e2f5833
28 files changed
+506
-194
No files matched your search
@@ -7,11 +7,10 @@ import (
|
||||
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/jwtutils"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
@@ -37,13 +36,20 @@ func Login(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, err := generarToken(*user, 15*time.Minute)
|
||||
usuarioConPermisos, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(user.ID)
|
||||
if err != nil {
|
||||
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 {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
||||
return
|
||||
}
|
||||
|
||||
refreshToken, err := generarToken(*user, 24*time.Hour)
|
||||
refreshToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeRefresh, permisos, 24*time.Hour)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate refresh token"})
|
||||
return
|
||||
@@ -54,18 +60,6 @@ func Login(c *gin.Context) {
|
||||
RefreshToken: refreshToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: 900,
|
||||
Permissions: permisos,
|
||||
})
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
+10
-42
@@ -2,64 +2,32 @@ package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/jwtutils"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
|
||||
"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"})
|
||||
userID, ok := c.Get("userID")
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "usuario no autenticado"})
|
||||
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 jwtutils.JWTSecret, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
id, ok := userID.(uint)
|
||||
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)
|
||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(uint(userID))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
permisos, _ := utils.PermisosDelContexto(c)
|
||||
|
||||
c.JSON(http.StatusOK, dto.MeResponse{
|
||||
ID: user.ID,
|
||||
Email: user.Email,
|
||||
Name: user.Name,
|
||||
ID: id,
|
||||
Email: c.GetString("email"),
|
||||
Name: c.GetString("name"),
|
||||
Permissions: permisos,
|
||||
})
|
||||
}
|
||||
@@ -7,9 +7,9 @@ import (
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/jwtutils"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func Refresh(c *gin.Context) {
|
||||
@@ -21,43 +21,32 @@ func Refresh(c *gin.Context) {
|
||||
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 jwtutils.JWTSecret, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
claims, err := jwtutils.ValidarTokenDeTipo(req.RefreshToken, jwtutils.TokenTypeRefresh)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid refresh token"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
sub, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
return
|
||||
}
|
||||
|
||||
sub, ok := claims["sub"].(float64)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
return
|
||||
}
|
||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(uint(sub))
|
||||
user, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(sub)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
permisos := utils.PermisosDeUsuario(user)
|
||||
|
||||
accessToken, err := generarToken(*user, 15*time.Minute)
|
||||
accessToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeAccess, permisos, 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)
|
||||
newRefreshToken, err := jwtutils.GenerarToken(user.ID, user.Email, user.Name, jwtutils.TokenTypeRefresh, permisos, 24*time.Hour)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate refresh token"})
|
||||
return
|
||||
@@ -68,5 +57,6 @@ func Refresh(c *gin.Context) {
|
||||
RefreshToken: newRefreshToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: 900,
|
||||
Permissions: permisos,
|
||||
})
|
||||
}
|
||||
+5
-3
@@ -5,6 +5,7 @@ type TokenResponse struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
Permissions []uint `json:"permissions"`
|
||||
}
|
||||
|
||||
type RegisterResponse struct {
|
||||
@@ -14,7 +15,8 @@ type RegisterResponse struct {
|
||||
}
|
||||
|
||||
type MeResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
ID uint `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Permissions []uint `json:"permissions"`
|
||||
}
|
||||
+177
-9
@@ -1,29 +1,88 @@
|
||||
package jwtutils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
var (
|
||||
JWTSecret []byte
|
||||
once sync.Once
|
||||
const (
|
||||
TokenTypeAccess = "access"
|
||||
TokenTypeRefresh = "refresh"
|
||||
|
||||
ClaimPermissions = "permissions"
|
||||
ClaimType = "typ"
|
||||
ClaimSubject = "sub"
|
||||
)
|
||||
|
||||
func ValidarJWT(tokenString string) (jwt.MapClaims, error) {
|
||||
var (
|
||||
jwtSecret []byte
|
||||
once sync.Once
|
||||
initErr error
|
||||
)
|
||||
|
||||
// Init carga el secreto JWT una sola vez y falla si no esta configurado.
|
||||
func Init() error {
|
||||
once.Do(func() {
|
||||
godotenv.Load()
|
||||
JWTSecret = []byte(os.Getenv("JWTString"))
|
||||
_ = godotenv.Load()
|
||||
secret := os.Getenv("JWTString")
|
||||
if secret == "" {
|
||||
initErr = errors.New("JWTString no esta definida en el entorno")
|
||||
return
|
||||
}
|
||||
jwtSecret = []byte(secret)
|
||||
})
|
||||
|
||||
return initErr
|
||||
}
|
||||
|
||||
// GetSecret devuelve el secreto JWT, inicializandolo si hace falta.
|
||||
func GetSecret() ([]byte, error) {
|
||||
if err := Init(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return jwtSecret, nil
|
||||
}
|
||||
|
||||
// GenerarToken firma un token HS256 con los datos del usuario y sus permisos planos.
|
||||
func GenerarToken(userID uint, email, name, tokenType string, permissions []uint, duration time.Duration) (string, error) {
|
||||
secret, err := GetSecret()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
claims := jwt.MapClaims{
|
||||
ClaimSubject: userID,
|
||||
"email": email,
|
||||
"name": name,
|
||||
ClaimPermissions: permissions,
|
||||
ClaimType: tokenType,
|
||||
"exp": time.Now().Add(duration).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(secret)
|
||||
}
|
||||
|
||||
// ValidarJWT verifica la firma HS256 y la expiracion del token.
|
||||
func ValidarJWT(tokenString string) (jwt.MapClaims, error) {
|
||||
secret, err := GetSecret()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
if token.Method.Alg() != jwt.SigningMethodHS256.Alg() {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return JWTSecret, nil
|
||||
return secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -36,3 +95,112 @@ func ValidarJWT(tokenString string) (jwt.MapClaims, error) {
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// ValidarTokenDeTipo valida la firma y exige el tipo de token esperado.
|
||||
func ValidarTokenDeTipo(tokenString, tokenType string) (jwt.MapClaims, error) {
|
||||
claims, err := ValidarJWT(tokenString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tipo, ok := claims[ClaimType].(string)
|
||||
if !ok || tipo != tokenType {
|
||||
return nil, errors.New("tipo de token invalido")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// ClaimUint convierte un claim numerico (JSON lo decodifica como float64) a uint.
|
||||
func ClaimUint(claims jwt.MapClaims, key string) (uint, bool) {
|
||||
value, ok := claims[key]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
switch v := value.(type) {
|
||||
case float64:
|
||||
if v < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return uint(v), true
|
||||
case int:
|
||||
if v < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return uint(v), true
|
||||
case int64:
|
||||
if v < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return uint(v), true
|
||||
case uint:
|
||||
return v, true
|
||||
case string:
|
||||
parsed, err := strconv.ParseUint(v, 10, 64)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return uint(parsed), true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
// PermisosDesdeClaims extrae la lista plana de IDs de permisos del token.
|
||||
func PermisosDesdeClaims(claims jwt.MapClaims) []uint {
|
||||
raw, ok := claims[ClaimPermissions]
|
||||
if !ok {
|
||||
return []uint{}
|
||||
}
|
||||
|
||||
permisos := make([]uint, 0)
|
||||
switch list := raw.(type) {
|
||||
case []interface{}:
|
||||
for _, item := range list {
|
||||
if id, ok := toUint(item); ok {
|
||||
permisos = append(permisos, id)
|
||||
}
|
||||
}
|
||||
case []uint:
|
||||
permisos = append(permisos, list...)
|
||||
case []float64:
|
||||
for _, item := range list {
|
||||
if item >= 0 {
|
||||
permisos = append(permisos, uint(item))
|
||||
}
|
||||
}
|
||||
case []int:
|
||||
for _, item := range list {
|
||||
if item >= 0 {
|
||||
permisos = append(permisos, uint(item))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return permisos
|
||||
}
|
||||
|
||||
func toUint(value any) (uint, bool) {
|
||||
switch v := value.(type) {
|
||||
case float64:
|
||||
if v < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return uint(v), true
|
||||
case int:
|
||||
if v < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return uint(v), true
|
||||
case int64:
|
||||
if v < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return uint(v), true
|
||||
case uint:
|
||||
return v, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package jwtutils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTokenRoundTrip(t *testing.T) {
|
||||
os.Setenv("JWTString", "test-secret")
|
||||
t.Cleanup(func() { os.Unsetenv("JWTString") })
|
||||
|
||||
token, err := GenerarToken(7, "a@b.c", "Nombre", TokenTypeAccess, []uint{1, 2, 4}, time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("generar token: %v", err)
|
||||
}
|
||||
|
||||
claims, err := ValidarTokenDeTipo(token, TokenTypeAccess)
|
||||
if err != nil {
|
||||
t.Fatalf("validar token: %v", err)
|
||||
}
|
||||
|
||||
if id, ok := ClaimUint(claims, ClaimSubject); !ok || id != 7 {
|
||||
t.Fatalf("sub esperado 7, obtenido %v (%v)", id, ok)
|
||||
}
|
||||
|
||||
if got := PermisosDesdeClaims(claims); !reflect.DeepEqual(got, []uint{1, 2, 4}) {
|
||||
t.Fatalf("permisos esperados [1 2 4], obtenidos %v", got)
|
||||
}
|
||||
|
||||
if _, err := ValidarTokenDeTipo(token, TokenTypeRefresh); err == nil {
|
||||
t.Fatal("un access token no deberia validar como refresh")
|
||||
}
|
||||
}
|
||||
+22
-15
@@ -10,7 +10,10 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AuthMiddleware() gin.HandlerFunc {
|
||||
// AuthMiddleware valida la firma del JWT y, opcionalmente, exige que el usuario
|
||||
// tenga al menos uno de los permisos indicados. Los permisos viajan en el claim
|
||||
// "permissions" como una lista plana de IDs.
|
||||
func AuthMiddleware(permisosRequeridos ...uint) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
@@ -26,16 +29,24 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := jwtutils.ValidarJWT(partes[1])
|
||||
claims, err := jwtutils.ValidarTokenDeTipo(partes[1], jwtutils.TokenTypeAccess)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token invalido o expirado"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if sub, ok := claims["sub"].(float64); ok {
|
||||
c.Set("userID", uint(sub))
|
||||
userID, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token invalido: usuario no encontrado"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
permisos := jwtutils.PermisosDesdeClaims(claims)
|
||||
c.Set("userID", userID)
|
||||
c.Set(utils.ContextPermissionsKey, permisos)
|
||||
|
||||
if email, ok := claims["email"].(string); ok {
|
||||
c.Set("email", email)
|
||||
}
|
||||
@@ -43,6 +54,12 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
c.Set("name", name)
|
||||
}
|
||||
|
||||
if len(permisosRequeridos) > 0 && !utils.UsuarioTieneAlgunPermiso(c, permisosRequeridos) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para realizar esta accion"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -60,7 +77,7 @@ func PermisoMiddleware(permisoID uint) gin.HandlerFunc {
|
||||
|
||||
func PermisosMiddleware(permisosIDs ...uint) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !UsuarioTieneAlgunPermiso(c, permisosIDs) {
|
||||
if !utils.UsuarioTieneAlgunPermiso(c, permisosIDs) {
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
"error": "No tienes permiso para realizar esta accion",
|
||||
})
|
||||
@@ -71,13 +88,3 @@ func PermisosMiddleware(permisosIDs ...uint) gin.HandlerFunc {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func UsuarioTieneAlgunPermiso(c *gin.Context, permisosIDs []uint) bool {
|
||||
for _, permisoID := range permisosIDs {
|
||||
if utils.UsuarioTienePermiso(c, permisoID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -29,7 +29,7 @@ type repositorioUsuario struct {
|
||||
}
|
||||
|
||||
func (r *repositorioUsuario) CantidadUsuarios(cant *int64) error {
|
||||
if err := r.db.Model(&models_seguridad.Usuario{}).Count(cant).Error; err!= nil {
|
||||
if err := r.db.Model(&models_seguridad.Usuario{}).Count(cant).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -90,11 +90,44 @@ func (r *repositorioUsuario) Eliminar(id uint) error {
|
||||
return r.db.Delete(&models_seguridad.Usuario{}, id).Error
|
||||
}
|
||||
|
||||
func (r *repositorioUsuario) cargarGruposPermisosRecursivo(grupo *models_seguridad.Grupo, visitados map[uint]bool) error {
|
||||
if visitados[grupo.ID] {
|
||||
// Evita ciclos en la jerarquia de grupos.
|
||||
grupo.Grupos = nil
|
||||
return nil
|
||||
}
|
||||
visitados[grupo.ID] = true
|
||||
|
||||
if err := r.db.
|
||||
Model(grupo).
|
||||
Preload("Permisos").
|
||||
Association("Grupos").
|
||||
Find(&grupo.Grupos); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i := range grupo.Grupos {
|
||||
if err := r.cargarGruposPermisosRecursivo(&grupo.Grupos[i], visitados); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repositorioUsuario) PrecargarGruposPermisosPorID(id uint) (*models_seguridad.Usuario, error) {
|
||||
var user models_seguridad.Usuario
|
||||
if err := r.db.Preload("Grupos.Permisos").Preload("Grupos.Grupos.Permisos").First(&user, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
visitados := make(map[uint]bool)
|
||||
for i := range user.Grupos {
|
||||
if err := r.cargarGruposPermisosRecursivo(&user.Grupos[i], visitados); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
@@ -132,8 +165,8 @@ func (r *repositorioUsuario) QuitarGrupoDeUsuario(usuarioID, grupoID uint) error
|
||||
}
|
||||
|
||||
if grupoID == 1 {
|
||||
cantidadAdmins :=tx.Model(&models_seguridad.Grupo{ID: grupoID}).Association("Usuarios").Count()
|
||||
if (cantidadAdmins<=1){
|
||||
cantidadAdmins := tx.Model(&models_seguridad.Grupo{ID: grupoID}).Association("Usuarios").Count()
|
||||
if cantidadAdmins <= 1 {
|
||||
return errors.New("No se puede eliminar al ultimo administrador")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ func AuthRoute(r *gin.Engine) {
|
||||
authGroup.POST("/login", auth.Login)
|
||||
authGroup.POST("/register", auth.Register)
|
||||
authGroup.POST("/refresh", auth.Refresh)
|
||||
authGroup.GET("/me", auth.Me)
|
||||
authGroup.GET("/me", middleware.AuthMiddleware(), auth.Me)
|
||||
authGroup.POST("/cambiar-contraseña", middleware.AuthMiddleware(), auth.CambiarContraseña)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func GroupRoute(r *gin.Engine) {
|
||||
groupGroup := r.Group("/grupos")
|
||||
groupGroup.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(2))
|
||||
groupGroup.Use(middleware.AuthMiddleware(2))
|
||||
{
|
||||
groupGroup.GET("/:id", grupo.ObtenerGrupo)
|
||||
groupGroup.POST("", grupo.CrearGrupo)
|
||||
@@ -21,7 +21,7 @@ func GroupRoute(r *gin.Engine) {
|
||||
groupGroup.DELETE("/:id/subgrupos", grupo.QuitarSubGrupo)
|
||||
}
|
||||
groupGroup2 := r.Group("/grupos")
|
||||
groupGroup2.Use(middleware.AuthMiddleware(), middleware.PermisosMiddleware(2,3))
|
||||
groupGroup2.Use(middleware.AuthMiddleware(2, 3))
|
||||
{
|
||||
groupGroup2.GET("", grupo.ObtenerGrupos)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func LogsRoute(r *gin.Engine) {
|
||||
repuestoGrupo := r.Group("/logs")
|
||||
repuestoGrupo.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(5))
|
||||
repuestoGrupo.Use(middleware.AuthMiddleware(5))
|
||||
{
|
||||
repuestoGrupo.GET("/:p/", logs.ObtenerLogs)
|
||||
repuestoGrupo.POST("/:p/busqueda", logs.BusquedaLogs)
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func MarcaRoute(r *gin.Engine) {
|
||||
marcaGrupo := r.Group("/marcas")
|
||||
marcaGrupo.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(5))
|
||||
marcaGrupo.Use(middleware.AuthMiddleware(5))
|
||||
{
|
||||
marcaGrupo.GET("/", marca.ObtenerMarcas)
|
||||
// marcaGrupo.GET("/:id", repuestos.ObtenerRepuesto)
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func PermisoRoute(r *gin.Engine) {
|
||||
permGroup := r.Group("/permisos")
|
||||
permGroup.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(1))
|
||||
permGroup.Use(middleware.AuthMiddleware(1))
|
||||
{
|
||||
permGroup.POST("", permiso.CrearPermiso)
|
||||
permGroup.PUT("/:id", permiso.ActualizarPermiso)
|
||||
@@ -17,7 +17,7 @@ func PermisoRoute(r *gin.Engine) {
|
||||
}
|
||||
|
||||
permGroup2 := r.Group("/permisos")
|
||||
permGroup2.Use(middleware.AuthMiddleware(), middleware.PermisosMiddleware(1, 3))
|
||||
permGroup2.Use(middleware.AuthMiddleware(1, 3))
|
||||
{
|
||||
permGroup2.GET("", permiso.ObtenerPermisos)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func RepuestoRoute(r *gin.Engine) {
|
||||
repuestoGrupo := r.Group("/repuestos")
|
||||
repuestoGrupo.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(4))
|
||||
repuestoGrupo.Use(middleware.AuthMiddleware(4))
|
||||
{
|
||||
repuestoGrupo.GET("/", repuestos.ObtenerRepuestos)
|
||||
repuestoGrupo.GET("/:id", repuestos.ObtenerRepuesto)
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
func UserRoute(r *gin.Engine) {
|
||||
userGroup := r.Group("/usuarios")
|
||||
userGroup.Use(middleware.AuthMiddleware(), middleware.PermisoMiddleware(3))
|
||||
userGroup.Use(middleware.AuthMiddleware(3))
|
||||
{
|
||||
userGroup.GET("", usuarios.ObtenerUsuarios)
|
||||
userGroup.GET("/:id", usuarios.ObtenerUsuario)
|
||||
|
||||
+54
-24
@@ -1,42 +1,72 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sort"
|
||||
|
||||
"repuestera_back/jwtutils"
|
||||
r "repuestera_back/repositorios"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const ContextPermissionsKey = "permissions"
|
||||
|
||||
// PermisosDeUsuario aplana la jerarquia completa de grupos y subgrupos en una
|
||||
// lista de IDs de permisos sin duplicados.
|
||||
func PermisosDeUsuario(usuario *models_seguridad.Usuario) []uint {
|
||||
permisosMap := make(map[uint]models_seguridad.Permiso)
|
||||
for i := range usuario.Grupos {
|
||||
usuario.Grupos[i].ListarPermisos(permisosMap)
|
||||
}
|
||||
|
||||
permisos := make([]uint, 0, len(permisosMap))
|
||||
for id := range permisosMap {
|
||||
permisos = append(permisos, id)
|
||||
}
|
||||
|
||||
sort.Slice(permisos, func(i, j int) bool {
|
||||
return permisos[i] < permisos[j]
|
||||
})
|
||||
|
||||
return permisos
|
||||
}
|
||||
|
||||
// PermisosDelContexto devuelve los permisos planos que dejo AuthMiddleware.
|
||||
func PermisosDelContexto(c *gin.Context) ([]uint, bool) {
|
||||
value, exists := c.Get(ContextPermissionsKey)
|
||||
if !exists {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
permisos, ok := value.([]uint)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return permisos, true
|
||||
}
|
||||
|
||||
// UsuarioTienePermiso chequea los permisos del contexto, sin volver a parsear
|
||||
// el token ni consultar la base de datos.
|
||||
func UsuarioTienePermiso(c *gin.Context, permisoID uint) bool {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
partes := strings.Split(authHeader, " ")
|
||||
if len(partes) != 2 || partes[0] != "Bearer" {
|
||||
return false
|
||||
}
|
||||
|
||||
claims, err := jwtutils.ValidarJWT(partes[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
sub, ok := claims["sub"].(float64)
|
||||
permisos, ok := PermisosDelContexto(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
usuario, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(uint(sub))
|
||||
if err != nil {
|
||||
return false
|
||||
for _, permiso := range permisos {
|
||||
if permiso == permisoID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
for _, grupo := range usuario.Grupos {
|
||||
if grupo.Buscar(permisoID) {
|
||||
return false
|
||||
}
|
||||
|
||||
// UsuarioTieneAlgunPermiso devuelve true si el usuario tiene al menos uno de
|
||||
// los permisos indicados.
|
||||
func UsuarioTieneAlgunPermiso(c *gin.Context, permisosIDs []uint) bool {
|
||||
for _, permisoID := range permisosIDs {
|
||||
if UsuarioTienePermiso(c, permisoID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,14 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import {
|
||||
getAuthTokens,
|
||||
setAuthTokens,
|
||||
setToken,
|
||||
getTokenExpiry,
|
||||
notifyAuthChange,
|
||||
removeAuthTokens,
|
||||
removeToken
|
||||
removeToken,
|
||||
setAuthTokens,
|
||||
setToken
|
||||
} from '$lib/hooks/token';
|
||||
|
||||
function getTokenExpiry(): number | null {
|
||||
try {
|
||||
const token = getAuthTokens()?.access_token;
|
||||
if (!token) return null;
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
return payload.exp ? payload.exp * 1000 : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
import { getCurrentUser, removeCurrentUser, setCurrentUser } from '$lib/hooks/user';
|
||||
|
||||
export class TokenRefresher {
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
@@ -80,13 +72,22 @@ export class TokenRefresher {
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
expires_in: data.expires_in,
|
||||
token_type: data.token_type
|
||||
token_type: data.token_type,
|
||||
permissions: data.permissions
|
||||
});
|
||||
setToken(data.access_token);
|
||||
|
||||
const currentUser = getCurrentUser();
|
||||
if (currentUser) {
|
||||
setCurrentUser({ ...currentUser, permissions: data.permissions ?? [] });
|
||||
}
|
||||
|
||||
this.schedule();
|
||||
} catch {
|
||||
removeAuthTokens();
|
||||
removeToken();
|
||||
removeCurrentUser();
|
||||
notifyAuthChange();
|
||||
this.stop();
|
||||
this.onExpired();
|
||||
}
|
||||
|
||||
@@ -14,17 +14,19 @@
|
||||
|
||||
interface Prop {
|
||||
usuario?: Usuario;
|
||||
grupos?: Promise<GruposYPermisosResponse> | {};
|
||||
grupos?: Promise<GruposYPermisosResponse>;
|
||||
}
|
||||
|
||||
let { usuario, grupos }: Prop = $props();
|
||||
|
||||
onMount(() => {
|
||||
if (typeof usuario === 'undefined') {
|
||||
usuario = getCurrentUser();
|
||||
usuario = getCurrentUser() ?? undefined;
|
||||
}
|
||||
if (typeof grupos === 'undefined') {
|
||||
grupos = usuario ? ObtenerGruposDeUsuario(usuario) : Promise.resolve({});
|
||||
grupos = usuario
|
||||
? ObtenerGruposDeUsuario(usuario)
|
||||
: Promise.resolve({ email: '', groups: [] });
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -35,7 +37,7 @@
|
||||
<HeaderNavItem text="Inicio" href="/" />
|
||||
<HeaderNavItem text="About" href="/about" />
|
||||
<HeaderNavItem text="Contact" href="/contact" />
|
||||
{:else}
|
||||
{:else if grupos}
|
||||
{#await grupos}
|
||||
<Breadcrumb noTrailingSlash skeleton count={3} />
|
||||
{:then g}
|
||||
|
||||
@@ -2,15 +2,17 @@
|
||||
import Logout from 'carbon-icons-svelte/lib/Logout.svelte';
|
||||
import ChevronDown from 'carbon-icons-svelte/lib/ChevronDown.svelte';
|
||||
import { getCurrentUser, removeCurrentUser } from '$lib/hooks/user';
|
||||
import { removeToken } from '$lib/hooks/token';
|
||||
import { notifyAuthChange, removeAuthTokens, removeToken } from '$lib/hooks/token';
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
let user = $state(getCurrentUser());
|
||||
let dropdownOpen = $state(false);
|
||||
|
||||
function handleLogout() {
|
||||
removeAuthTokens();
|
||||
removeToken();
|
||||
removeCurrentUser();
|
||||
notifyAuthChange();
|
||||
goto('/login');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import type { Usuario, GruposYPermisosResponse } from '../../types';
|
||||
import { API_URL } from '../env';
|
||||
import { getToken, removeToken, removeAuthTokens } from './token';
|
||||
import { getToken, notifyAuthChange, removeToken, removeAuthTokens } from './token';
|
||||
import { removeCurrentUser } from './user';
|
||||
|
||||
//Se usa en la parte del menu donde se obtienen los grupos y permisos para mostrar
|
||||
@@ -10,10 +10,11 @@ async function handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ message: 'Error desconocido' }));
|
||||
console.log(error);
|
||||
if (error.error) {
|
||||
if (response.status === 401) {
|
||||
removeToken();
|
||||
removeAuthTokens();
|
||||
removeCurrentUser();
|
||||
notifyAuthChange();
|
||||
goto('/login');
|
||||
}
|
||||
throw new Error(error.message || error.error || 'Error en la petición');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { LoginRequest, LoginResponse } from '../../types';
|
||||
import { API_URL } from '../env';
|
||||
import { setAuthTokens, setToken } from './token';
|
||||
import { decodeJwtPayload, notifyAuthChange, setAuthTokens, setToken } from './token';
|
||||
import { setCurrentUser } from './user';
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
@@ -17,14 +17,31 @@ export async function login(credentials: LoginRequest): Promise<LoginResponse> {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(credentials)
|
||||
});
|
||||
const data = await handleResponse<LoginResponse & { id: number }>(response);
|
||||
const data = await handleResponse<LoginResponse>(response);
|
||||
|
||||
setAuthTokens({
|
||||
access_token: data.access_token,
|
||||
expires_in: data.expires_in,
|
||||
refresh_token: data.refresh_token,
|
||||
token_type: data.token_type
|
||||
token_type: data.token_type,
|
||||
permissions: data.permissions
|
||||
});
|
||||
setCurrentUser({ id: data.id, email: credentials.email, name: credentials.email[0] });
|
||||
setToken(data.access_token);
|
||||
|
||||
const payload = decodeJwtPayload<{
|
||||
sub?: number | string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
permissions?: number[];
|
||||
}>(data.access_token);
|
||||
|
||||
setCurrentUser({
|
||||
id: Number(payload?.sub ?? 0),
|
||||
email: payload?.email ?? credentials.email,
|
||||
name: payload?.name ?? credentials.email,
|
||||
permissions: payload?.permissions ?? data.permissions ?? []
|
||||
});
|
||||
notifyAuthChange();
|
||||
|
||||
return data;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LoginResponse } from '../../types';
|
||||
import type { RegisterResponse } from '../../types';
|
||||
import { API_URL } from '../env';
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
@@ -13,11 +13,11 @@ export async function register(data: {
|
||||
email: string;
|
||||
password: string;
|
||||
name: string;
|
||||
}): Promise<LoginResponse> {
|
||||
}): Promise<RegisterResponse> {
|
||||
const response = await fetch(`${API_URL}/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
return handleResponse<LoginResponse>(response);
|
||||
return handleResponse<RegisterResponse>(response);
|
||||
}
|
||||
@@ -3,8 +3,11 @@ export interface AuthTokens {
|
||||
refresh_token: string;
|
||||
expires_in: number;
|
||||
token_type: string;
|
||||
permissions?: number[];
|
||||
}
|
||||
|
||||
export const AUTH_CHANGE_EVENT = 'auth-change';
|
||||
|
||||
export function setToken(token: string): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('token', token);
|
||||
@@ -43,3 +46,38 @@ export function removeAuthTokens(): void {
|
||||
localStorage.removeItem('auth');
|
||||
}
|
||||
}
|
||||
|
||||
export function getPermissions(): number[] {
|
||||
return getAuthTokens()?.permissions ?? [];
|
||||
}
|
||||
|
||||
export function notifyAuthChange(): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new Event(AUTH_CHANGE_EVENT));
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeJwtPayload<T = Record<string, unknown>>(token: string): T | null {
|
||||
try {
|
||||
const part = token.split('.')[1];
|
||||
if (!part) return null;
|
||||
|
||||
const base64 = part.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const padding = (4 - (base64.length % 4)) % 4;
|
||||
const padded = base64 + '='.repeat(padding);
|
||||
|
||||
const binary = atob(padded);
|
||||
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
||||
return JSON.parse(new TextDecoder().decode(bytes)) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getTokenExpiry(): number | null {
|
||||
const token = getAuthTokens()?.access_token;
|
||||
if (!token) return null;
|
||||
|
||||
const payload = decodeJwtPayload<{ exp?: number }>(token);
|
||||
return payload?.exp ? payload.exp * 1000 : null;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { User } from '../../types';
|
||||
import type { Usuario } from '../../types';
|
||||
|
||||
export function getCurrentUser(): User | null {
|
||||
export function getCurrentUser(): Usuario | null {
|
||||
if (typeof window !== 'undefined') {
|
||||
const user = localStorage.getItem('user');
|
||||
if (user == 'undefined') return null;
|
||||
@@ -9,7 +9,7 @@ export function getCurrentUser(): User | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function setCurrentUser(user: User): void {
|
||||
export function setCurrentUser(user: Usuario): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import './layout.css';
|
||||
import 'carbon-components-svelte/css/all.css';
|
||||
import favicon from '$lib/assets/favicon.svg';
|
||||
import { getToken } from '$lib/hooks/token';
|
||||
import { AUTH_CHANGE_EVENT, getToken } from '$lib/hooks/token';
|
||||
import { goto } from '$app/navigation';
|
||||
import { TokenRefresher } from '$lib/TokenRefresher.svelte';
|
||||
|
||||
@@ -14,6 +14,20 @@
|
||||
document.documentElement.setAttribute('theme', theme);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const syncToken = () => {
|
||||
token = getToken();
|
||||
};
|
||||
|
||||
window.addEventListener(AUTH_CHANGE_EVENT, syncToken);
|
||||
window.addEventListener('storage', syncToken);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(AUTH_CHANGE_EVENT, syncToken);
|
||||
window.removeEventListener('storage', syncToken);
|
||||
};
|
||||
});
|
||||
|
||||
let _refresher: TokenRefresher;
|
||||
|
||||
$effect(() => {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import LandingPage from '$lib/components/LandingPage.svelte';
|
||||
|
||||
let usuario = getCurrentUser();
|
||||
let usuario = getCurrentUser() ?? undefined;
|
||||
let grupos = usuario ? ObtenerGruposDeUsuario(usuario) : undefined;
|
||||
</script>
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { BpmnLinkOutline } from 'carbon-icons-svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let usuario = getCurrentUser();
|
||||
let usuario = getCurrentUser() ?? undefined;
|
||||
|
||||
onMount(() => {
|
||||
if (!usuario) goto('/login');
|
||||
|
||||
Vendored
+28
-18
@@ -2,6 +2,7 @@ export interface Usuario {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
permissions?: number[];
|
||||
}
|
||||
|
||||
export interface CrearRepuestoDto {
|
||||
@@ -80,32 +81,41 @@ export interface LoginResponse {
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
permissions: number[];
|
||||
}
|
||||
|
||||
token: string;
|
||||
access_token;
|
||||
user: User;
|
||||
export interface RegisterResponse {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
permissions: number[];
|
||||
}
|
||||
|
||||
export interface BaseModel {
|
||||
ID: number;
|
||||
CreatedAt: string;
|
||||
UpdatedAt: string;
|
||||
DeletedAt?: string | null;
|
||||
ID: number;
|
||||
CreatedAt: string;
|
||||
UpdatedAt: string;
|
||||
DeletedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface Marca extends BaseModel {
|
||||
nombre: string;
|
||||
repuestos: Repuesto[];
|
||||
nombre: string;
|
||||
repuestos: Repuesto[];
|
||||
}
|
||||
|
||||
|
||||
export interface Repuesto extends BaseModel {
|
||||
nombre: string;
|
||||
descripcion: string;
|
||||
precio: number;
|
||||
stockMinimo: number;
|
||||
marcaId: number;
|
||||
marca: Marca | string;
|
||||
aliases: string[];
|
||||
// stocks?: Stock[]; // opcional si tienes entidad Stock
|
||||
nombre: string;
|
||||
descripcion: string;
|
||||
precio: number;
|
||||
stockMinimo: number;
|
||||
marcaId: number;
|
||||
marca: Marca | string;
|
||||
aliases: string[];
|
||||
// stocks?: Stock[]; // opcional si tienes entidad Stock
|
||||
}
|
||||
Reference in new issue
Block a user