-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAuthProvider.tsx
158 lines (141 loc) · 4.63 KB
/
AuthProvider.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import * as React from "react";
import { UnregisteredAccount } from "../../model/account";
import auth0 from "auth0-js";
import nanoid from "nanoid";
import { RouteComponentProps, withRouter } from "react-router";
import IdleTimer from "react-idle-timer";
import { StringParam, useQueryParam } from "use-query-params";
const CLIENT_ID = process.env.REACT_APP_AUTH0_CLIENT_ID!;
const DOMAIN = process.env.REACT_APP_AUTH0_DOMAIN!;
const IDLE_TIMEOUT = 1000 * 60 * 30;
const REDIRECT_URI = `${window.location.origin}/callback`;
const TARGET_PARAM = "returnTo";
export const auth0Client = new auth0.WebAuth({
domain: DOMAIN,
clientID: CLIENT_ID,
redirectUri: REDIRECT_URI,
responseType: "token id_token",
scope: "openid profile email"
});
export const login = () => {
const returnToURL = encodeURIComponent(
`${window.location.pathname}${window.location.search}`
);
auth0Client.authorize({
redirectUri: `${REDIRECT_URI}?${TARGET_PARAM}=${returnToURL}`,
nonce: nanoid()
});
};
export const logout = () => {
auth0Client.logout({ returnTo: window.location.origin });
};
interface IUserInfo {
idToken: string;
user: UnregisteredAccount;
}
export type IAuthData =
| { state: "loading" }
| { state: "logged-out" }
| {
state: "logged-in";
userInfo: IUserInfo;
};
export const AuthContext = React.createContext<IAuthData>({ state: "loading" });
const AuthProvider: React.FunctionComponent<RouteComponentProps> = props => {
const [authData, setAuthData] = React.useState<IAuthData>({
state: "loading"
});
const checkSession = React.useCallback(() => {
auth0Client.checkSession({}, (err, res) => {
if (err?.code === "login_required") {
// Don't automatically log in if the user is visiting the home page
if (props.history.location.pathname === "/") {
setAuthData({ state: "logged-out" });
} else {
login();
}
} else {
const {
email,
given_name,
family_name,
picture
} = res.idTokenPayload;
setAuthData({
state: "logged-in",
userInfo: {
idToken: res.idToken as string,
user: {
email,
first_n: given_name,
last_n: family_name,
picture
}
}
});
}
});
}, [props.history.location.pathname]);
const targetPath = useQueryParam(TARGET_PARAM, StringParam)[0];
const onRedirectCallback = React.useCallback(() => {
// Do not redirect to targetPath that starts with "/callback",
// since this would lead to recursive redirection.
if (targetPath && !targetPath.startsWith("/callback")) {
props.history.push(targetPath);
} else {
props.history.push("/");
}
}, [props.history, targetPath]);
React.useEffect(() => {
if (props.location.pathname === "/logout") {
logout();
return;
}
if (props.location.pathname === "/callback") {
onRedirectCallback();
return;
}
if (authData.state !== "logged-in") {
checkSession();
}
}, [
props.location,
authData.state,
props.location.pathname,
checkSession,
onRedirectCallback
]);
return (
<AuthContext.Provider value={authData}>
<IdleTimer
ref={() => null}
onIdle={logout}
timeout={IDLE_TIMEOUT}
/>
{props.children}
</AuthContext.Provider>
);
};
export default withRouter(AuthProvider);
/**
* Inject the current user's identity token into the wrapped component as a prop
* called token. If auth data is loading, the component won't be rendered. If
* the current user is not logged in, the component will be rendered with an undefined
* `token` prop.
*/
export function withIdToken<P>(
Component: React.ComponentType<any>
): React.FunctionComponent<P> {
return (props: any) => {
const auth = React.useContext(AuthContext);
if (auth.state === "loading") {
return null;
}
return (
<Component
{...props}
token={auth.state === "logged-in" && auth.userInfo.idToken}
/>
);
};
}