diff --git a/web/src/lib/pb.ts b/web/src/lib/pb.ts new file mode 100644 index 0000000..83d5705 --- /dev/null +++ b/web/src/lib/pb.ts @@ -0,0 +1,13 @@ +import PocketBase, { ClientResponseError } from 'pocketbase'; + +export const pb = new PocketBase(typeof window === 'undefined' ? 'http://127.0.0.1:8080' : window.location.origin); +pb.autoCancellation(false); + +/** User facing message of any error, preferring the message PocketBase sent. */ +export function errorMessage(e: unknown): string { + if (e instanceof ClientResponseError) { + const message = (e.response as { message?: unknown } | undefined)?.message; + if (typeof message === 'string' && message) return message; + } + return e instanceof Error ? e.message : String(e); +} diff --git a/web/src/lib/session.svelte.ts b/web/src/lib/session.svelte.ts new file mode 100644 index 0000000..2925bd1 --- /dev/null +++ b/web/src/lib/session.svelte.ts @@ -0,0 +1,82 @@ +import { closeDb, currentUserId, openDb, wipeLocal } from '$lib/db.svelte'; +import { errorMessage, pb } from '$lib/pb'; + +export const session = $state({ + userId: '' as string, + email: '' as string, + checked: false +}); + +export type Gate = 'login' | 'app'; + +/** First field error PocketBase sent, else the general message of the error. */ +function authError(e: unknown): string { + const data = (e as { response?: { data?: Record } }).response?.data; + const first = data ? Object.entries(data)[0] : undefined; + if (first) return `${first[0]}: ${first[1]?.message ?? 'invalid'}`; + return errorMessage(e); +} + +export async function refreshAuth(): Promise { + if (!pb.authStore.isValid) return; + try { + await pb.collection('users').authRefresh(); + } catch (e) { + const status = (e as { status?: number }).status; + if (status === 401 || status === 403 || status === 404) pb.authStore.clear(); + } +} + +async function activate(): Promise { + const r = pb.authStore.record; + if (!r) throw new Error('Not signed in'); + session.userId = r.id; + session.email = String(r.email ?? ''); + await openDb(r.id); + session.checked = true; +} + +export async function resolveGate(): Promise { + await refreshAuth(); + if (!pb.authStore.isValid || !pb.authStore.record) { + session.userId = ''; + session.email = ''; + session.checked = true; + return 'login'; + } + await activate(); + return 'app'; +} + +export async function login(email: string, password: string): Promise { + try { + await pb.collection('users').authWithPassword(email, password); + } catch (e) { + throw new Error(authError(e)); + } + await activate(); +} + +export async function signup(email: string, password: string): Promise { + try { + await pb.collection('users').create({ email, password, passwordConfirm: password }); + await pb.collection('users').authWithPassword(email, password); + } catch (e) { + throw new Error(authError(e)); + } + await activate(); +} + +export async function logout(): Promise { + const uid = session.userId || pb.authStore.record?.id || currentUserId(); + await closeDb(); + if (uid) await wipeLocal(uid); + pb.authStore.clear(); + session.userId = ''; + session.email = ''; +} + +export function safeNext(url: URL, fallback = '/today'): string { + const n = url.searchParams.get('next'); + return n && n.startsWith('/') && !/^\/[\\/]/.test(n) ? n : fallback; +}