diff --git a/app/services/auth.ts b/app/services/auth.ts new file mode 100644 index 0000000..791bab5 --- /dev/null +++ b/app/services/auth.ts @@ -0,0 +1,37 @@ +import { pb } from '~/services/pocketbase'; + +const USERS_COLLECTION = 'users'; + +// "Keep me signed in" off: the session must end when the browser closes. A cookie without an expiry +// date is dropped with the browser, so the flag surviving in localStorage without it means a restart. +const SESSION_ONLY_KEY = 'ar_session_only'; +const SESSION_COOKIE = 'ar_session'; +const hasSessionCookie = () => new RegExp(`(?:^|; )${SESSION_COOKIE}=`).test(document.cookie); + +function endClosedBrowserSession() { + if (typeof window === 'undefined' || !localStorage.getItem(SESSION_ONLY_KEY) || hasSessionCookie()) return; + localStorage.removeItem(SESSION_ONLY_KEY); + pb.authStore.clear(); +} + +export function isSignedIn() { + endClosedBrowserSession(); + return pb.authStore.isValid; +} + +export const currentUserEmail = (): string | undefined => pb.authStore.record?.email; + +export async function signIn(email: string, password: string, remember: boolean) { + await pb.collection(USERS_COLLECTION).authWithPassword(email, password); + if (remember) { + localStorage.removeItem(SESSION_ONLY_KEY); + return; + } + localStorage.setItem(SESSION_ONLY_KEY, '1'); + document.cookie = `${SESSION_COOKIE}=1; path=/; SameSite=Lax`; +} + +export function signOut() { + localStorage.removeItem(SESSION_ONLY_KEY); + pb.authStore.clear(); +}