Private
Public Access
91 lines
2.3 KiB
Go
91 lines
2.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"repuestera_back/jwtutils"
|
|
"repuestera_back/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// 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 == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: Header Authorization no presente"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
partes := strings.Split(authHeader, " ")
|
|
if len(partes) != 2 || partes[0] != "Bearer" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Formato de token invalido"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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)
|
|
}
|
|
if name, ok := claims["name"].(string); ok {
|
|
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()
|
|
}
|
|
}
|
|
|
|
func PermisoMiddleware(permisoID uint) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if !utils.UsuarioTienePermiso(c, permisoID) {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para realizar esta accion"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func PermisosMiddleware(permisosIDs ...uint) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if !utils.UsuarioTieneAlgunPermiso(c, permisosIDs) {
|
|
c.JSON(http.StatusForbidden, gin.H{
|
|
"error": "No tienes permiso para realizar esta accion",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|