apifiber/middlewares/authentication.go

53 lines
1.2 KiB
Go

package middlewares
import (
"api/config"
"api/models"
"api/services"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
)
var usr models.User
func Authenticate(c *fiber.Ctx) error {
tk := c.Get("Authorization")
if tk == "" {
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: No token provided")
}
tokenstr := strings.Split(tk, " ")[1]
token, err := jwt.Parse(tokenstr, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Conf.ApiSecret), nil
})
if err != nil {
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: "+strings.Replace(err.Error(), "token has invalid claims: ", "", -1))
}
if token.Valid {
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
usr = services.GetUser(claims["iss"].(string))
if usr.Blocked == "S" {
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User blocked")
}
if usr.Cancelled == "S" {
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User cancelled")
}
c.Locals("user", usr)
return c.Next()
}
}
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: Invalid token")
}