-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthenticator.js
60 lines (45 loc) · 1.53 KB
/
Authenticator.js
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
import { useState, useContext, createContext, useEffect } from 'react'
import { firebaseauth } from './InitFirebase'
import nookies from "nookies";
// CTX
const AuthContext = createContext({
user: null
})
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState();
useEffect(() => {
if (typeof window !== "undefined") {
window.nookies = nookies;
}
return firebaseauth.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: '/'});
});
}, []);
// Fo rce refresh token every 10 mins
useEffect(() => {
const handle = setInterval(async () => {
console.log("refreshing token")
const user = firebaseauth.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);
};