48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import { redirect } from '@sveltejs/kit';
|
|
import type { Actions, PageServerLoad } from './$types';
|
|
import { APIError } from '$lib/api/request';
|
|
import { getLoggedInUser, login, logout } from '$lib/api/auth';
|
|
|
|
export const load = async function ({ url, cookies }) {
|
|
const session = cookies.get('session');
|
|
|
|
// Check that login is valid
|
|
if (session) {
|
|
let user: string | null = null;
|
|
try {
|
|
user = await getLoggedInUser(cookies);
|
|
} catch (e) {
|
|
// do nothing if not logged in
|
|
}
|
|
if (user) {
|
|
throw redirect(302, url.searchParams.get('then') || '/admin');
|
|
}
|
|
}
|
|
} satisfies PageServerLoad;
|
|
|
|
export const actions = {
|
|
login: async ({ cookies, request, url }) => {
|
|
const data = await request.formData();
|
|
const username = data.get('username')?.toString();
|
|
const password = data.get('password')?.toString();
|
|
if (!username || !password) return { error: 'missing credentials' };
|
|
|
|
try {
|
|
await login(cookies, username, password);
|
|
} catch (e) {
|
|
if (e instanceof APIError) {
|
|
switch (e.code) {
|
|
case 'invalid-login':
|
|
return { error: 'invalid credentials' };
|
|
}
|
|
}
|
|
return { error: 'unknown internal error' };
|
|
}
|
|
throw redirect(302, url.searchParams.get('then') || '/admin');
|
|
},
|
|
logout: async ({ url, cookies }) => {
|
|
await logout(cookies);
|
|
throw redirect(302, url.searchParams.get('then') || '/login');
|
|
}
|
|
} satisfies Actions;
|