feat: add auth service with keep me signed in
This commit is contained in:
parent
14bc5047fb
commit
c4e9f2aeaa
37
app/services/auth.ts
Normal file
37
app/services/auth.ts
Normal file
@ -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();
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user