This repository has been archived by the owner on Feb 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
react-auth0-spa.tsx
141 lines (125 loc) · 3.99 KB
/
react-auth0-spa.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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// @ts-nocheck
import Auth0Client from "@auth0/auth0-spa-js/dist/typings/Auth0Client";
import { isEqualWith, pick } from "lodash";
import React, { useContext, useEffect, useState } from "react";
import { getUser, saveUser } from "../database";
const DEFAULT_REDIRECT_CALLBACK = () =>
window.history.replaceState({}, document.title, window.location.pathname);
export const Auth0Context = React.createContext();
export const useAuth0 = () => {
// Note: useContext() appears to return undefined when compiling statically.
// We should look into that.
return useContext(Auth0Context) || {};
};
interface Props {
onRedirectCallback: () => void;
auth0ClientPromise: Promise<Auth0Client>;
}
export const Auth0Provider: React.FC<Props> = ({
children,
onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
auth0ClientPromise,
}) => {
const [isAuthenticated, setIsAuthenticated] = useState();
const [user, setUser] = useState();
const [auth0Client, setAuth0Client] = useState();
const [loading, setLoading] = useState(true);
const [popupOpen, setPopupOpen] = useState(false);
useEffect(() => {
const initAuth0 = async () => {
let auth0Client = await auth0ClientPromise;
setAuth0Client(auth0Client);
if (
window.location.search.includes("code=") &&
window.location.search.includes("state=")
) {
const { appState } = await auth0Client.handleRedirectCallback();
onRedirectCallback(appState);
}
const isAuthenticated = await auth0Client.isAuthenticated();
setIsAuthenticated(isAuthenticated);
if (isAuthenticated) {
const user = await auth0Client.getUser();
setUser(user);
}
setLoading(false);
};
initAuth0();
// eslint-disable-next-line
}, []);
const loginWithPopup = async (params = {}) => {
setPopupOpen(true);
try {
await auth0Client.loginWithPopup(params);
} catch (error) {
console.error(error);
} finally {
setPopupOpen(false);
}
const user = await auth0Client.getUser();
setUser(user);
setIsAuthenticated(true);
};
const handleRedirectCallback = async () => {
setLoading(true);
await auth0Client.handleRedirectCallback();
const user = await auth0Client.getUser();
setLoading(false);
setIsAuthenticated(true);
setUser(user);
};
// This hook is specific to our application and not derived from Auth0 example code
useEffect(() => {
async function updateStoredUser() {
if (user !== undefined) {
const savedUser = await getUser(user.sub);
if (!savedUser) {
// this is expected, as auth0 users predate this feature.
// we can lazy-migrate them into our user database by
// creating a record now.
saveUser({
name: user.name,
email: user.email,
auth0Id: user.sub,
});
} else {
// if anything has changed, update our records.
// this anoints Auth0 as the ultimate source of truth
// for user info, synced at the beginning of a session
if (
!isEqualWith(
savedUser,
user,
(a, b) => a.name === b.name && a.email === b.email,
)
) {
saveUser({
...savedUser,
...pick(user, ["email", "name"]),
});
}
}
}
}
updateStoredUser();
}, [user]);
return (
<Auth0Context.Provider
value={{
isAuthenticated,
user,
loading,
popupOpen,
loginWithPopup,
handleRedirectCallback,
getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
getTokenSilently: (...p) => auth0Client.getTokenSilently(...p),
getTokenWithPopup: (...p) => auth0Client.getTokenWithPopup(...p),
logout: (...p) => auth0Client.logout(...p),
}}
>
{children}
</Auth0Context.Provider>
);
};