customer/internal/utils/authenticator.go

65 lines
1.3 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"
2024-11-18 07:23:41 +00:00
"gitea.pena/PenaSide/customer/internal/errors"
"gitea.pena/PenaSide/customer/internal/models"
2023-06-22 09:36:43 +00:00
)
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 strings.TrimPrefix(header, prefix), nil
}
2024-06-08 17:34:40 +00:00
token := c.Query("Authorization")
if token == "" {
2023-06-22 09:36:43 +00:00
return "", errors.New(
fmt.Errorf("failed to parse jws from request: no valid token found"),
2023-06-22 09:36:43 +00:00
errors.ErrNoAccess,
)
}
return token, nil
2023-06-22 09:36:43 +00:00
}