-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathauth.ts
45 lines (40 loc) · 1.28 KB
/
auth.ts
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
33
34
35
36
37
38
39
40
41
42
43
44
45
import { readable, writable } from "svelte/store";
import { onAuthStateChanged, type Auth, type User } from "firebase/auth";
/**
* @param {Auth} auth firebase auth instance
* @param {any} startWith optional default data. Useful for server-side cookie-based auth
* @returns a store with the current firebase user
* user != null -> signed in
* user == null -> signed out
* user == undefined -> still loading auth status on initial page load -> show loading spinner or sth else to prevent a normally signed in user from seeing content as a signed out user for a second
*/
export function userStore(auth: Auth, startWith = undefined) {
let unsubscribe: () => void;
// Fallback for SSR
if (!globalThis.window) {
const { subscribe } = readable(startWith);
return {
subscribe,
};
}
// Fallback for missing SDK
if (!auth) {
console.warn(
"Firebase Auth is not initialized. Are you missing FirebaseApp as a parent component?"
);
const { subscribe } = readable(undefined);
return {
subscribe,
};
}
const { subscribe } = readable<User | null | undefined>(
auth.currentUser ?? undefined,
(set) => {
const unsubscribe = onAuthStateChanged(auth, set);
return () => unsubscribe();
}
);
return {
subscribe,
};
}