43 lines
1.2 KiB
TypeScript
43 lines
1.2 KiB
TypeScript
import { redirect } from '@sveltejs/kit';
|
|
import type { Actions, PageServerLoad } from './$types';
|
|
|
|
export const load: PageServerLoad = async ({ url, locals }) => {
|
|
if (locals.user) {
|
|
throw redirect(303, url.searchParams.get('redirectTo') ?? '/');
|
|
}
|
|
return {
|
|
redirectTo: url.searchParams.get('redirectTo') ?? '',
|
|
error: null
|
|
};
|
|
};
|
|
|
|
export const actions: Actions = {
|
|
default: async ({ request, locals, url }) => {
|
|
const formData = await request.formData();
|
|
const email = String(formData.get('email') ?? '').trim();
|
|
const password = String(formData.get('password') ?? '');
|
|
const redirectTo = String(formData.get('redirectTo') ?? '').trim() || '/';
|
|
|
|
if (!email || !password) {
|
|
return {
|
|
redirectTo,
|
|
error: 'Email and password are required.'
|
|
};
|
|
}
|
|
|
|
try {
|
|
await locals.pb.collection('users').authWithPassword(email, password);
|
|
} catch (err) {
|
|
const message = err && typeof err === 'object' && 'message' in err
|
|
? String((err as { message: string }).message)
|
|
: 'Invalid email or password.';
|
|
return {
|
|
redirectTo,
|
|
error: message
|
|
};
|
|
}
|
|
|
|
throw redirect(303, redirectTo);
|
|
}
|
|
};
|