~james/core

core/web/src/lib/auth/guards.ts -rw-r--r-- 1.1 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { goto } from "$app/navigation";
import { resolve } from "$app/paths";
import { redirect, type RequestEvent } from "@sveltejs/kit";
import { CURRENT_DID_KEY, CURRENT_HANDLE_KEY } from "#lib/auth/accounts.ts";
import type { Auth } from "#lib/auth.svelte.ts";

export interface RequireAuthResult {
	did: string;
	handle: string;
}

export const loginWithReturn = (returnUrl: string): string =>
	`/login?return_url=${encodeURIComponent(returnUrl)}`;

export const loginHrefFor = (url: Pick<URL, "pathname" | "search">) =>
	resolve(loginWithReturn(url.pathname + url.search) as "/login");

export const requireAuth = (event: RequestEvent): RequireAuthResult => {
	const did = event.cookies.get(CURRENT_DID_KEY);
	if (!did) {
		redirect(302, loginWithReturn(event.url.pathname + event.url.search));
	}
	return { did, handle: event.cookies.get(CURRENT_HANDLE_KEY) ?? did };
};

export const requireAuthClient = (auth: Auth, url: URL): boolean => {
	if (auth.currentDid) return true;
	void goto(resolve(loginWithReturn(url.pathname + url.search) as "/login"), {
		replace: true
	});
	return false;
};