♻️ Improve code structure and much easier to read
🐛 Fix auth middleware
This commit is contained in:
@ -17,23 +17,23 @@ var (
|
||||
authContextCache = make(map[string]models.AuthContext)
|
||||
)
|
||||
|
||||
func Authenticate(access, refresh string, depth int) (ctx models.AuthContext, perms map[string]any, newAccess, newRefresh string, err error) {
|
||||
func Authenticate(atk, rtk string, rty int) (ctx models.AuthContext, perms map[string]any, newAtk, newRtk string, err error) {
|
||||
var claims PayloadClaims
|
||||
claims, err = DecodeJwt(access)
|
||||
claims, err = DecodeJwt(atk)
|
||||
if err != nil {
|
||||
if len(refresh) > 0 && depth < 1 {
|
||||
if len(rtk) > 0 && rty < 1 {
|
||||
// Auto refresh and retry
|
||||
newAccess, newRefresh, err = RefreshToken(refresh)
|
||||
newAtk, newRtk, err = RefreshToken(rtk)
|
||||
if err == nil {
|
||||
return Authenticate(newAccess, newRefresh, depth+1)
|
||||
return Authenticate(newAtk, newRtk, rty+1)
|
||||
}
|
||||
}
|
||||
err = fiber.NewError(fiber.StatusUnauthorized, fmt.Sprintf("invalid auth key: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
newAccess = access
|
||||
newRefresh = refresh
|
||||
newAtk = atk
|
||||
newRtk = rtk
|
||||
|
||||
if ctx, err = GetAuthContext(claims.ID); err == nil {
|
||||
var heldPerms map[string]any
|
||||
|
@ -2,16 +2,12 @@ package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var CookieAccessKey = "passport_auth_key"
|
||||
var CookieRefreshKey = "passport_refresh_key"
|
||||
|
||||
type PayloadClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
|
||||
@ -60,22 +56,3 @@ func DecodeJwt(str string) (PayloadClaims, error) {
|
||||
return claims, fmt.Errorf("unexpected token payload: not payload claims type")
|
||||
}
|
||||
}
|
||||
|
||||
func SetJwtCookieSet(c *fiber.Ctx, access, refresh string) {
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: CookieAccessKey,
|
||||
Value: access,
|
||||
Domain: viper.GetString("security.cookie_domain"),
|
||||
SameSite: viper.GetString("security.cookie_samesite"),
|
||||
Expires: time.Now().Add(60 * time.Minute),
|
||||
Path: "/",
|
||||
})
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: CookieRefreshKey,
|
||||
Value: refresh,
|
||||
Domain: viper.GetString("security.cookie_domain"),
|
||||
SameSite: viper.GetString("security.cookie_samesite"),
|
||||
Expires: time.Now().Add(24 * 30 * time.Hour),
|
||||
Path: "/",
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user