migrate auth v2 code

This commit is contained in:
JCEEE
2026-08-16 10:11:39 +01:00
parent 3dd94b8a7c
commit c73ced7894
45 changed files with 1965 additions and 1519 deletions
+31 -19
View File
@@ -1,10 +1,12 @@
import { fail, redirect } from '@sveltejs/kit';
import { login, setSessionCookie, setPbTokenCookie } from '$lib/server/auth';
import { createPbClient } from '$lib/server/pocketbase';
import { setSessionCookie } from '$lib/server/session';
import { pbAdmin } from '$lib/server/pocketbase';
import { handleOf } from '@shared/slugify';
export const actions = {
default: async (event) => {
const fd = await event.request.formData();
default: async (event) => {
const fd = await event.request.formData();
const email = fd.get('email') as string;
const password = fd.get('password') as string;
@@ -12,22 +14,32 @@ export const actions = {
return fail(400, { error: 'Email and password required', email });
}
let result: any;
let authResult: { token: string; record: any };
try {
result = await login(email, password);
} catch (e) {
return fail(400, { error: e instanceof Error ? e.message : 'Login failed', email });
authResult = await createPbClient()
.collection('users')
.authWithPassword(email, password);
} catch {
return fail(400, { error: 'Invalid email or password', email });
}
setSessionCookie(event, {
famId: result.famId,
userId: result.userId,
famSlug: result.famSlug,
memberName: result.memberName,
role: result.role,
});
setPbTokenCookie(event, result.token);
const user = authResult.record;
if (!user.famId) {
return fail(400, { error: 'No family linked to this account', email });
}
throw redirect(303, `/${result.famSlug}/${result.memberName}`);
},
};
setSessionCookie(event.cookies, authResult.token);
const fam = await pbAdmin.getOne('fams', user.famId).catch(() => null);
const famSlug = fam?.slug || user.famId;
// Parents (admins) land on the fam dashboard — no username in the URL.
if (user.role === 'parent') {
throw redirect(303, `/${famSlug}`);
}
// Children don't log in via email; this is just a safe fallback.
const handle = handleOf(user.username || '') || user.name || email.split('@')[0];
throw redirect(303, `/${famSlug}/${handle}`);
}
};