-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.tsx
51 lines (44 loc) · 1.46 KB
/
auth.tsx
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
import React, { useState, useEffect, useContext, createContext } from "react";
import nookies from "nookies";
import { firebaseClient } from "./firebaseClient";
const AuthContext = createContext<{ user: firebaseClient.User | null }>({
user: null,
});
export function AuthProvider({ children }: any) {
const [user, setUser] = useState<firebaseClient.User | null>(null);
useEffect(() => {
if (typeof window !== "undefined") {
(window as any).nookies = nookies;
}
return firebaseClient.auth().onIdTokenChanged(async (user) => {
console.log(`token changed!`);
if (!user) {
console.log(`no token found...`);
setUser(null);
nookies.destroy(null, "token");
nookies.set(null, "token", "", {path: '/'});
return;
}
console.log(`updating token...`);
const token = await user.getIdToken();
setUser(user);
nookies.destroy(null, "token");
nookies.set(null, "token", token, {path: '/'});
});
}, []);
// force refresh the token every 10 minutes
useEffect(() => {
const handle = setInterval(async () => {
console.log(`refreshing token...`);
const user = firebaseClient.auth().currentUser;
if (user) await user.getIdToken(true);
}, 10 * 60 * 1000);
return () => clearInterval(handle);
}, []);
return (
<AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
);
}
export const useAuth = () => {
return useContext(AuthContext);
};