customer/internal/utils/authenticator.go

60 lines
1.2 KiB
Go
Raw Normal View History

2023-06-22 09:36:43 +00:00
package utils
import (
"fmt"
2024-05-20 12:32:59 +00:00
"github.com/gofiber/fiber/v2"
2023-06-22 09:36:43 +00:00
"strings"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
)
const (
prefix = "Bearer "
)
2024-05-20 12:32:59 +00:00
func NewAuthenticator(jwtUtil *JWT) fiber.Handler {
return func(c *fiber.Ctx) error {
2023-06-22 09:36:43 +00:00
if jwtUtil == nil {
2024-05-20 12:32:59 +00:00
return fiber.NewError(fiber.StatusInternalServerError, errors.ErrInvalidArgs.Error())
2023-06-22 09:36:43 +00:00
}
2024-05-20 12:32:59 +00:00
err := authenticate(jwtUtil, c)
if err != nil {
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
}
2023-06-22 09:36:43 +00:00
2024-05-20 12:32:59 +00:00
return c.Next()
2023-06-22 09:36:43 +00:00
}
2024-05-20 12:32:59 +00:00
}
2023-06-22 09:36:43 +00:00
2024-05-20 12:32:59 +00:00
func authenticate(jwtUtil *JWT, c *fiber.Ctx) error {
jws, err := parseJWSFromRequest(c)
2023-06-22 09:36:43 +00:00
if err != nil {
return err
}
2023-06-29 14:50:48 +00:00
userID, validateErr := jwtUtil.Validate(jws)
2023-06-22 09:36:43 +00:00
if validateErr != nil {
return validateErr
}
2024-05-20 12:32:59 +00:00
c.Locals(models.AuthJWTDecodedUserIDKey, userID)
c.Locals(models.AuthJWTDecodedAccessTokenKey, jws)
2023-06-22 09:36:43 +00:00
return nil
}
2024-05-20 12:32:59 +00:00
func parseJWSFromRequest(c *fiber.Ctx) (string, error) {
header := c.Get("Authorization")
2023-06-22 09:36:43 +00:00
if header == "" || !strings.HasPrefix(header, prefix) {
return "", errors.New(
fmt.Errorf("failed to parse jws from request header: %s", header),
errors.ErrNoAccess,
)
}
return strings.TrimPrefix(header, prefix), nil
}