From bdcef60cab6a61e1717661e918c42e3650d23fee Mon Sep 17 00:00:00 2001 From: Elias Schneider Date: Wed, 4 Jun 2025 08:52:34 +0200 Subject: [PATCH] fix: don't load app config and user on every route change --- frontend/src/{hooks.ts => hooks.client.ts} | 4 +-- frontend/src/lib/utils/redirection-util.ts | 25 +++++++++++++++++ frontend/src/routes/+layout.svelte | 8 ++++++ frontend/src/routes/+layout.ts | 31 +--------------------- 4 files changed, 36 insertions(+), 32 deletions(-) rename frontend/src/{hooks.ts => hooks.client.ts} (75%) create mode 100644 frontend/src/lib/utils/redirection-util.ts diff --git a/frontend/src/hooks.ts b/frontend/src/hooks.client.ts similarity index 75% rename from frontend/src/hooks.ts rename to frontend/src/hooks.client.ts index f71323e7..2f9fb085 100644 --- a/frontend/src/hooks.ts +++ b/frontend/src/hooks.client.ts @@ -1,7 +1,7 @@ -import type { HandleServerError } from '@sveltejs/kit'; +import type { HandleClientError } from '@sveltejs/kit'; import { AxiosError } from 'axios'; -export const handleError: HandleServerError = async ({ error, message, status }) => { +export const handleError: HandleClientError = async ({ error, message, status }) => { if (error instanceof AxiosError) { message = error.response?.data.error || message; status = error.response?.status || status; diff --git a/frontend/src/lib/utils/redirection-util.ts b/frontend/src/lib/utils/redirection-util.ts new file mode 100644 index 00000000..a927cac4 --- /dev/null +++ b/frontend/src/lib/utils/redirection-util.ts @@ -0,0 +1,25 @@ +import type { User } from '$lib/types/user.type'; + +// Returns the path to redirect to based on the current path and user authentication status +// If no redirect is needed, it returns null +export function getAuthRedirectPath(path: string, user: User | null) { + const isSignedIn = !!user; + const isAdmin = user?.isAdmin; + + const isUnauthenticatedOnlyPath = + path == '/login' || path.startsWith('/login/') || path == '/lc' || path.startsWith('/lc/'); + const isPublicPath = ['/authorize', '/device', '/health', '/healthz'].includes(path); + const isAdminPath = path == '/settings/admin' || path.startsWith('/settings/admin/'); + + if (!isUnauthenticatedOnlyPath && !isPublicPath && !isSignedIn) { + return '/login'; + } + + if (isUnauthenticatedOnlyPath && isSignedIn) { + return '/settings'; + } + + if (isAdminPath && !isAdmin) { + return '/settings'; + } +} diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte index 25999ab3..5b9dffbe 100644 --- a/frontend/src/routes/+layout.svelte +++ b/frontend/src/routes/+layout.svelte @@ -1,4 +1,6 @@