42 lines
950 B
Go
42 lines
950 B
Go
package middlewares
|
|
|
|
import (
|
|
"BE-MiniERP/config"
|
|
"strings"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
)
|
|
|
|
func JWTProtected() fiber.Handler {
|
|
return func(c *fiber.Ctx) error {
|
|
authHeader := c.Get("Authorization")
|
|
if authHeader == "" {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
|
"message": "Missing Authorization header",
|
|
})
|
|
}
|
|
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(config.GetConfig().JWTSecret), nil
|
|
})
|
|
|
|
if err != nil || !token.Valid {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
|
"message": "Invalid or expired token",
|
|
})
|
|
}
|
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
|
"message": "Invalid token claims",
|
|
})
|
|
}
|
|
|
|
c.Locals("user", claims)
|
|
return c.Next()
|
|
}
|
|
}
|