The userGroup hook was hardcoding http://localhost:8080 instead of reading API_INTERNAL_URL from the environment. In Docker this caused the /api/users/me fetch to fail silently, leaving event.locals.user unset and triggering the handleAuth guard to redirect every page to /login — including the login form action itself, creating an infinite redirect loop. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
78 lines
2.4 KiB
TypeScript
78 lines
2.4 KiB
TypeScript
import { redirect, type Handle, type HandleFetch } from '@sveltejs/kit';
|
|
import { paraglideMiddleware } from '$lib/paraglide/server';
|
|
import { sequence } from '@sveltejs/kit/hooks';
|
|
import { env } from 'process';
|
|
|
|
const PUBLIC_PATHS = ['/login', '/logout'];
|
|
|
|
const handleAuth: Handle = async ({ event, resolve }) => {
|
|
const isPublic = PUBLIC_PATHS.some((p) => event.url.pathname.startsWith(p));
|
|
if (!isPublic && !event.locals.user) {
|
|
throw redirect(302, '/login');
|
|
}
|
|
return resolve(event);
|
|
};
|
|
|
|
const handleParaglide: Handle = ({ event, resolve }) => paraglideMiddleware(event.request, ({ request, locale }) => {
|
|
event.request = request;
|
|
|
|
return resolve(event, {
|
|
transformPageChunk: ({ html }) => html.replace('%paraglide.lang%', locale)
|
|
});
|
|
});
|
|
|
|
|
|
const userGroup: Handle = async ({ event, resolve }) => {
|
|
const auth = event.cookies.get('auth_token');
|
|
|
|
if (auth) {
|
|
try {
|
|
const apiUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
|
|
const response = await fetch(`${apiUrl}/api/users/me`, {
|
|
headers: { Authorization: auth }
|
|
|
|
});
|
|
if (response.ok) {
|
|
const user = await response.json();
|
|
event.locals.user = user;
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching user in hook:', error);
|
|
}
|
|
}
|
|
|
|
return resolve(event);
|
|
};
|
|
|
|
|
|
export const handleFetch: HandleFetch = async ({ event, request, fetch }) => {
|
|
const apiUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
|
|
const isApi = request.url.startsWith(apiUrl) || request.url.includes('/api/');
|
|
const isNotLoginTest = !request.url.includes('/api/users/me');
|
|
|
|
if (isApi && isNotLoginTest) {
|
|
const token = event.cookies.get('auth_token');
|
|
|
|
if (!token) {
|
|
return new Response('Unauthorized', { status: 401 });
|
|
}
|
|
|
|
// Clone the request first to preserve the body
|
|
const clonedRequest = request.clone();
|
|
|
|
// Create new request with Authorization header and preserved body
|
|
const modifiedRequest = new Request(clonedRequest, {
|
|
headers: {
|
|
...Object.fromEntries(clonedRequest.headers),
|
|
'Authorization': token
|
|
}
|
|
});
|
|
|
|
return fetch(modifiedRequest);
|
|
}
|
|
|
|
return fetch(request);
|
|
};
|
|
|
|
export const handle = sequence(userGroup, handleAuth, handleParaglide);
|