[READ-ONLY] Mirror of https://github.com/flo-bit/svelte-cloudflare-statusphere.
statusphere.atmo.tools
atproto
cloudflare-workers
oauth
svelte
1.2 kB
43 lines
1import type { Cookies } from '@sveltejs/kit';
2import { Client } from '@atcute/client';
3import type { Did } from '@atcute/lexicons';
4import type { OAuthSession } from '@atcute/oauth-node-client';
5import { createOAuthClient } from './oauth';
6import { getSignedCookie } from './signed-cookie';
7
8export type SessionLocals = {
9 session: OAuthSession | null;
10 client: Client | null;
11 did: Did | null;
12};
13
14/**
15 * Restores an OAuth session from the signed `did` cookie.
16 * Returns session locals to be assigned to `event.locals`.
17 * Deletes the cookie if the session can't be restored.
18 */
19export async function restoreSession(
20 cookies: Cookies,
21 env?: App.Platform['env']
22): Promise<SessionLocals> {
23 const did = getSignedCookie(cookies, 'did') as Did | null;
24
25 if (!did) {
26 return { session: null, client: null, did: null };
27 }
28
29 try {
30 const oauth = createOAuthClient(env);
31 const session = await oauth.restore(did);
32
33 return {
34 session,
35 client: new Client({ handler: session }),
36 did
37 };
38 } catch (e) {
39 console.error('Failed to restore session:', e);
40 cookies.delete('did', { path: '/' });
41 return { session: null, client: null, did: null };
42 }
43}