feat: adminPath in config.json now drives actual route rewriting via server hook

This commit is contained in:
Falkan
2026-03-17 20:30:56 -04:00
parent e7752ad4ca
commit 9e9040d998
4 changed files with 56 additions and 1 deletions

36
src/hooks.server.ts Normal file
View File

@@ -0,0 +1,36 @@
import { loadConfig } from '$lib/server/data';
import type { Handle } from '@sveltejs/kit';
/**
* Rewrites requests from the configured adminPath to the internal /admin route.
*
* Example: if adminPath = "secret-panel", then:
* /secret-panel → /admin
* /secret-panel/login → /admin/login
* /secret-panel/api/units → /admin/api/units
*
* If adminPath = "admin" (default), this is a no-op.
*/
export const handle: Handle = async ({ event, resolve }) => {
const config = loadConfig();
const adminPath = (config.adminPath ?? 'admin').replace(/^\/|\/$/g, '');
if (adminPath !== 'admin') {
const url = event.url;
const prefix = `/${adminPath}`;
if (url.pathname === prefix || url.pathname.startsWith(prefix + '/')) {
// Rewrite the URL to use /admin internally
const rewritten = '/admin' + url.pathname.slice(prefix.length);
event.url = new URL(rewritten + url.search + url.hash, url.origin);
// Also update request.url so auth helpers see the rewritten path
Object.defineProperty(event.request, 'url', {
value: event.url.toString(),
writable: false,
configurable: true
});
}
}
return resolve(event);
};

View File

@@ -1,5 +1,6 @@
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 }) => {
@@ -14,7 +15,9 @@ export const load: LayoutServerLoad = ({ request, url }) => {
}
if (!authRequest(request)) {
throw redirect(302, '/admin/login');
// Redirect to login using the configured admin path so the URL stays consistent
const adminPath = (loadConfig().adminPath ?? 'admin').replace(/^\/|\/$/g, '');
throw redirect(302, `/${adminPath}/login`);
}
return { authenticated: true };