31 lines
663 B
Go
31 lines
663 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.SendStatus(fiber.StatusUnauthorized)
|
|
}
|
|
|
|
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.SendStatus(fiber.StatusUnauthorized)
|
|
}
|
|
|
|
c.Locals("user", token.Claims)
|
|
return c.Next()
|
|
}
|
|
}
|