♻️ Improve code structure and much easier to read

🐛 Fix auth middleware
This commit is contained in:
2024-06-22 13:04:21 +08:00
parent c37a55b88b
commit 7007cda8f2
34 changed files with 451 additions and 337 deletions

View File

@ -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

View File

@ -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: "/",
})
}