feat: adminPath from config.json rewrites route at startup via reroute hook

This commit is contained in:
Falkan
2026-03-17 20:40:38 -04:00
parent 51f047df3e
commit c044f98aa6
2 changed files with 30 additions and 3 deletions

27
src/hooks.ts Normal file
View File

@@ -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 /<adminPath>/... 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;
};

View File

@@ -1,20 +1,20 @@
import { redirect } from '@sveltejs/kit'; import { redirect } from '@sveltejs/kit';
import { authRequest } from '$lib/server/auth'; import { authRequest } from '$lib/server/auth';
import { loadConfig } from '$lib/server/data';
import type { LayoutServerLoad } from './$types'; import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = ({ request, url }) => { export const load: LayoutServerLoad = ({ request, url }) => {
// Skip auth check for the login page itself
if (url.pathname.endsWith('/login') || url.pathname.endsWith('/login/')) { if (url.pathname.endsWith('/login') || url.pathname.endsWith('/login/')) {
return { authenticated: false }; return { authenticated: false };
} }
// API routes handle their own auth — layout data isn't consumed by +server.ts
if (url.pathname.includes('/api/')) { if (url.pathname.includes('/api/')) {
return {}; return {};
} }
if (!authRequest(request)) { if (!authRequest(request)) {
throw redirect(302, '/admin/login'); const adminPath = (loadConfig().adminPath ?? 'admin').replace(/^\/|\/$/g, '');
throw redirect(302, `/${adminPath}/login`);
} }
return { authenticated: true }; return { authenticated: true };