1import { replaceState } from '$app/navigation';
2import { addAccount, loggingIn } from '$lib/accounts';
3import { AtpClient } from '$lib/at/client';
4import { flow } from '$lib/at/oauth';
5import { err, ok, type Result } from '$lib/result';
6import type { PageLoad } from './$types';
7
8export type PageProps = {
9 data: {
10 client: Result<AtpClient | null, string>;
11 };
12};
13
14export const load: PageLoad = async (): Promise<PageProps['data']> => {
15 return { client: await handleLogin() };
16};
17
18const handleLogin = async (): Promise<Result<AtpClient | null, string>> => {
19 const account = loggingIn.get();
20 if (!account) return ok(null);
21
22 const currentUrl = new URL(window.location.href);
23 // scrub history so auth state cant be replayed
24 try {
25 replaceState('', '/');
26 } catch {
27 // if router was unitialized then we probably dont need to scrub anyway
28 // so its fine
29 }
30
31 loggingIn.set(null);
32 const agent = await flow.finalize(currentUrl);
33 if (!agent.ok || !agent.value) {
34 if (!agent.ok) {
35 return err(agent.error);
36 }
37 return err('no session was logged into?!');
38 }
39
40 const client = new AtpClient();
41 const result = await client.login(account.did, agent.value);
42 if (!result.ok) {
43 return err(result.error);
44 }
45
46 addAccount(account);
47 return ok(client);
48};