From c044f98aa6c4c68b33d6104a9e730aaa75fe74ad Mon Sep 17 00:00:00 2001 From: Falkan Date: Tue, 17 Mar 2026 20:40:38 -0400 Subject: [PATCH] feat: adminPath from config.json rewrites route at startup via reroute hook --- src/hooks.ts | 27 +++++++++++++++++++++++++++ src/routes/admin/+layout.server.ts | 6 +++--- 2 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 src/hooks.ts diff --git a/src/hooks.ts b/src/hooks.ts new file mode 100644 index 0000000..81d10d3 --- /dev/null +++ b/src/hooks.ts @@ -0,0 +1,27 @@ +import fs from 'fs'; +import path from 'path'; +import type { Reroute } from '@sveltejs/kit'; + +// Read adminPath once at startup. Changes require a server restart. +let adminPath = 'admin'; +try { + const config = JSON.parse(fs.readFileSync(path.resolve('data', 'config.json'), 'utf8')); + adminPath = (config.adminPath ?? 'admin').replace(/^\/|\/$/g, ''); +} catch { + // config.json missing or unreadable — fall back to 'admin' +} + +/** + * Rewrites //... to /admin/... before SvelteKit resolves the route. + * No-op when adminPath is 'admin' (the default). + */ +export const reroute: Reroute = ({ url }) => { + if (adminPath === 'admin') return url.pathname; + + const prefix = `/${adminPath}`; + if (url.pathname === prefix || url.pathname.startsWith(prefix + '/')) { + return '/admin' + url.pathname.slice(prefix.length); + } + + return url.pathname; +}; diff --git a/src/routes/admin/+layout.server.ts b/src/routes/admin/+layout.server.ts index bfb46d4..c17568c 100644 --- a/src/routes/admin/+layout.server.ts +++ b/src/routes/admin/+layout.server.ts @@ -1,20 +1,20 @@ import { redirect } from '@sveltejs/kit'; import { authRequest } from '$lib/server/auth'; +import { loadConfig } from '$lib/server/data'; import type { LayoutServerLoad } from './$types'; export const load: LayoutServerLoad = ({ request, url }) => { - // Skip auth check for the login page itself if (url.pathname.endsWith('/login') || url.pathname.endsWith('/login/')) { return { authenticated: false }; } - // API routes handle their own auth — layout data isn't consumed by +server.ts if (url.pathname.includes('/api/')) { return {}; } if (!authRequest(request)) { - throw redirect(302, '/admin/login'); + const adminPath = (loadConfig().adminPath ?? 'admin').replace(/^\/|\/$/g, ''); + throw redirect(302, `/${adminPath}/login`); } return { authenticated: true };