feat: adminPath from config.json rewrites route at startup via reroute hook
This commit is contained in:
27
src/hooks.ts
Normal file
27
src/hooks.ts
Normal 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;
|
||||
};
|
||||
@@ -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 };
|
||||
|
||||
Reference in New Issue
Block a user