From 2cdae976d1ac25610750ce18c65435e1fbd2506f Mon Sep 17 00:00:00 2001 From: Kamil Marczak Date: Mon, 9 Dec 2024 21:04:04 +0100 Subject: [PATCH] fix: middleware fixes wiem bartus ze ci sie pewnie nie spodoba i chcialbys po prostu zrobic caly middleware w try catch i sama funkcja auth() jak w poprzednich tylko problem jest taki ze musze tak czy siak wykonac auth() zeby se uswierzytelnic za kazdym razem usera czy ma sesje a po tym doperio wykonac reszte logiki taka jak next jesli nie jest protected, wiec musialem tak zrobic --- frontend/src/lib/auth/index.ts | 9 +++++++++ frontend/src/middleware.ts | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/frontend/src/lib/auth/index.ts b/frontend/src/lib/auth/index.ts index 8443d4b..a02346a 100644 --- a/frontend/src/lib/auth/index.ts +++ b/frontend/src/lib/auth/index.ts @@ -103,6 +103,9 @@ export const auth = async (tokens?: { tokens?.secret ?? cookies.get("access_token_secret")?.value; if (accessToken === "" || accessSecret === "") { + if (tokens) { + return null; + } throw new Error("No access token or access secret"); } @@ -132,6 +135,9 @@ export const auth = async (tokens?: { name: "access_token_secret", path: "/", }); + if (tokens) { + return null; + } throw new Error(data.error); } const setCookieHeaders = response.headers.getSetCookie(); @@ -149,6 +155,9 @@ export const auth = async (tokens?: { }); return data; } catch (error) { + if (tokens) { + return null; + } throw new Error("Failed to authenticate"); } }; diff --git a/frontend/src/middleware.ts b/frontend/src/middleware.ts index 7863f45..83d2aa7 100644 --- a/frontend/src/middleware.ts +++ b/frontend/src/middleware.ts @@ -10,13 +10,13 @@ export async function middleware(request: NextRequest) { }; const isProtectedRoute = request.nextUrl.pathname.startsWith("/account"); - const isLogged = await auth(tokens); + const user = await auth(tokens); if (!isProtectedRoute) { return NextResponse.next(); } - if (!isLogged) { + if (user === null) { return NextResponse.redirect(new URL("/", request.url)); }