44 lines
1.2 KiB
Go
44 lines
1.2 KiB
Go
package httpserver
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
|
|
jwtutil "github.com/SamuelTariku/FortuneBet-Backend/internal/web_server/jwt"
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
func (a *App) authMiddleware(c *fiber.Ctx) error {
|
|
|
|
authHeader := c.Get("Authorization")
|
|
if authHeader == "" {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Authorization header missing")
|
|
}
|
|
|
|
if !strings.HasPrefix(authHeader, "Bearer ") {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Invalid authorization header format")
|
|
}
|
|
|
|
accessToken := strings.TrimPrefix(authHeader, "Bearer ")
|
|
c.Locals("access_token", accessToken)
|
|
claim, err := jwtutil.ParseJwt(accessToken, a.JwtConfig.JwtAccessKey)
|
|
if err != nil {
|
|
if errors.Is(err, jwtutil.ErrExpiredToken) {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Access token expired")
|
|
}
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Invalid access token")
|
|
}
|
|
|
|
refreshToken := c.Get("Refresh-Token")
|
|
if refreshToken == "" {
|
|
|
|
// refreshToken = c.Cookies("refresh_token", "")
|
|
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Refresh token missing")
|
|
}
|
|
c.Locals("user_id", claim.UserId)
|
|
c.Locals("role", claim.Role)
|
|
c.Locals("refresh_token", refreshToken)
|
|
return c.Next()
|
|
}
|