38 lines
1.3 KiB
TypeScript
38 lines
1.3 KiB
TypeScript
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();
|
|
}
|