-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
auth.ts
78 lines (62 loc) · 1.99 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* SPDX-FileCopyrightText: 2014-present Kriasoft */
/* SPDX-License-Identifier: MIT */
import {
GoogleAuthProvider,
User,
UserCredential,
getAuth,
signInAnonymously,
signInWithPopup,
} from "firebase/auth";
import { atom, useAtomValue } from "jotai";
import { loadable } from "jotai/utils";
import { useCallback, useState } from "react";
import { useNavigate } from "react-router-dom";
import { app, auth } from "./firebase";
import { store } from "./store";
export const currentUser = atom<Promise<User | null> | User | null>(
new Promise<User | null>(() => {}),
);
currentUser.debugLabel = "currentUser";
const unsubscribe = auth.onAuthStateChanged((user) => {
store.set(currentUser, user);
});
if (import.meta.hot) {
import.meta.hot.dispose(() => unsubscribe());
}
export function useCurrentUser() {
return useAtomValue(currentUser);
}
export const currentUserLoadable = loadable(currentUser);
export function useCurrentUserLoadable() {
return useAtomValue(currentUserLoadable);
}
export function useSignIn(
signInMethod: SignInMethod,
): [signIn: () => void, inFlight: boolean] {
const navigate = useNavigate();
const [inFlight, setInFlight] = useState(false);
const signIn = useCallback(() => {
let p: Promise<UserCredential> | null = null;
if (signInMethod === "anonymous") {
const auth = getAuth(app);
p = signInAnonymously(auth);
}
if (signInMethod === "google.com") {
const auth = getAuth(app);
const provider = new GoogleAuthProvider();
provider.addScope("profile");
provider.addScope("email");
provider.setCustomParameters({
// login_hint: ...
prompt: "consent",
});
p = signInWithPopup(auth, provider);
}
if (!p) throw new Error(`Not supported: ${signInMethod}`);
setInFlight(true);
p.then(() => navigate("/")).finally(() => setInFlight(false));
}, [signInMethod, navigate]);
return [signIn, inFlight] as const;
}
export type SignInMethod = "google.com" | "anonymous";