Private
Public Access
60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"repuestera_back/jwtutils"
|
|
"repuestera_back/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func AuthMiddleware() 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.ValidarJWT(partes[1])
|
|
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))
|
|
}
|
|
if email, ok := claims["email"].(string); ok {
|
|
c.Set("email", email)
|
|
}
|
|
if name, ok := claims["name"].(string); ok {
|
|
c.Set("name", name)
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|