Files
mealprep/frontend/src/routes/(public)/login/+page.server.ts
Marcel Raddatz 16f0feb8d5 fix(auth): fix mock responses in tests and block open redirect in login
- Add response object to mockSuccess() in login and signup tests so
  response.headers.get() no longer throws
- Validate ?redirect= param: must start with / and not // to prevent
  redirecting users to external domains

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 18:48:48 +02:00

48 lines
1.4 KiB
TypeScript

import { redirect, fail } from '@sveltejs/kit';
import { apiClient } from '$lib/server/api';
import type { Actions } from './$types';
export const actions = {
default: async ({ request, url, fetch, cookies }) => {
const formData = await request.formData();
const email = (formData.get('email') ?? '').toString().trim();
const password = (formData.get('password') ?? '').toString();
const errors: Record<string, string> = {};
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
errors.email = 'Ungültige E-Mail-Adresse';
}
if (!password) {
errors.password = 'Passwort ist erforderlich';
}
if (Object.keys(errors).length > 0) {
return fail(400, { errors, email });
}
const api = apiClient(fetch);
const { error, response } = await api.POST('/v1/auth/login', {
body: { email, password }
});
if (error) {
return fail(400, {
errors: { form: 'E-Mail oder Passwort ist falsch.' },
email
});
}
const sessionId = response.headers.get('set-cookie')?.match(/JSESSIONID=([^;]+)/i)?.[1];
if (sessionId) {
cookies.set('JSESSIONID', sessionId, { path: '/', httpOnly: true, sameSite: 'lax' });
}
const raw = url.searchParams.get('redirect');
const redirectTo = raw && raw.startsWith('/') && !raw.startsWith('//') ? raw : '/planner';
throw redirect(303, redirectTo);
}
} satisfies Actions;