Private
Public Access
añadido middleware de auth
This commit is contained in:
1 parent
63b52f6b97
commit
ab4ab106a9
6 files changed
+65
-47
No files matched your search
@@ -0,0 +1,59 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user