-
Notifications
You must be signed in to change notification settings - Fork 65
/
AuthProvider.tsx
307 lines (277 loc) · 10.1 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import React from "react";
import { UserManager, type UserManagerSettings, User } from "oidc-client-ts";
import type {
ProcessResourceOwnerPasswordCredentialsArgs,
SignoutResponse,
} from "oidc-client-ts";
import { AuthContext } from "./AuthContext";
import { initialAuthState } from "./AuthState";
import { reducer } from "./reducer";
import { hasAuthParams, signinError, signoutError } from "./utils";
/**
* @public
*/
export interface AuthProviderBaseProps {
/**
* The child nodes your Provider has wrapped
*/
children?: React.ReactNode;
/**
* On sign in callback hook. Can be a async function.
* Here you can remove the code and state parameters from the url when you are redirected from the authorize page.
*
* ```jsx
* const onSigninCallback = (_user: User | undefined): void => {
* window.history.replaceState(
* {},
* document.title,
* window.location.pathname
* )
* }
* ```
*/
onSigninCallback?: (user: User | undefined) => Promise<void> | void;
/**
* By default, if the page url has code/state params, this provider will call automatically the `userManager.signinCallback`.
* In some cases the code might be for something else (another OAuth SDK perhaps). In these
* instances you can instruct the client to ignore them.
*
* ```jsx
* <AuthProvider
* skipSigninCallback={window.location.pathname === "/stripe-oauth-callback"}
* >
* ```
*/
skipSigninCallback?: boolean;
/**
* Match the redirect uri used for logout (e.g. `post_logout_redirect_uri`)
* This provider will then call automatically the `userManager.signoutCallback`.
*
* HINT:
* Do not call `userManager.signoutRedirect()` within a `React.useEffect`, otherwise the
* logout might be unsuccessful.
*
* ```jsx
* <AuthProvider
* matchSignoutCallback={(args) => {
* window &&
* (window.location.href === args.post_logout_redirect_uri);
* }}
* ```
*/
matchSignoutCallback?: (args: UserManagerSettings) => boolean;
/**
* On sign out callback hook. Can be a async function.
* Here you can change the url after the user is signed out.
* When using this, specifying `matchSignoutCallback` is required.
*
* ```jsx
* const onSignoutCallback = (resp: SignoutResponse | undefined): void => {
* // go to home after logout
* window.location.pathname = ""
* }
* ```
*/
onSignoutCallback?: (resp: SignoutResponse | undefined) => Promise<void> | void;
/**
* On remove user hook. Can be a async function.
* Here you can change the url after the user is removed.
*
* ```jsx
* const onRemoveUser = (): void => {
* // go to home after logout
* window.location.pathname = ""
* }
* ```
*/
onRemoveUser?: () => Promise<void> | void;
}
/**
* This interface (default) is used to pass `UserManagerSettings` together with `AuthProvider` properties to the provider.
*
* @public
*/
export interface AuthProviderNoUserManagerProps extends AuthProviderBaseProps, UserManagerSettings {
/**
* Prevent this property.
*/
userManager?: never;
}
/**
* This interface is used to pass directly a `UserManager` instance together with `AuthProvider` properties to the provider.
*
* @public
*/
export interface AuthProviderUserManagerProps extends AuthProviderBaseProps {
/**
* Allow passing a custom UserManager instance.
*/
userManager?: UserManager;
}
/**
* @public
*/
export type AuthProviderProps = AuthProviderNoUserManagerProps | AuthProviderUserManagerProps;
const userManagerContextKeys = [
"clearStaleState",
"querySessionStatus",
"revokeTokens",
"startSilentRenew",
"stopSilentRenew",
] as const;
const navigatorKeys = [
"signinPopup",
"signinSilent",
"signinRedirect",
"signinResourceOwnerCredentials",
"signoutPopup",
"signoutRedirect",
"signoutSilent",
] as const;
const unsupportedEnvironment = (fnName: string) => () => {
throw new Error(
`UserManager#${fnName} was called from an unsupported context. If this is a server-rendered page, defer this call with useEffect() or pass a custom UserManager implementation.`,
);
};
const UserManagerImpl =
typeof window === "undefined" ? null : UserManager;
/**
* Provides the AuthContext to its child components.
*
* @public
*/
export const AuthProvider = (props: AuthProviderProps): JSX.Element => {
const {
children,
onSigninCallback,
skipSigninCallback,
matchSignoutCallback,
onSignoutCallback,
onRemoveUser,
userManager: userManagerProp = null,
...userManagerSettings
} = props;
const [userManager] = React.useState(() => {
return userManagerProp ??
(UserManagerImpl
? new UserManagerImpl(userManagerSettings as UserManagerSettings)
: ({ settings: userManagerSettings } as UserManager));
});
const [state, dispatch] = React.useReducer(reducer, initialAuthState);
const userManagerContext = React.useMemo(
() =>
Object.assign(
{
settings: userManager.settings,
events: userManager.events,
},
Object.fromEntries(
userManagerContextKeys.map((key) => [
key,
userManager[key]?.bind(userManager) ??
unsupportedEnvironment(key),
]),
) as Pick<UserManager, typeof userManagerContextKeys[number]>,
Object.fromEntries(
navigatorKeys.map((key) => [
key,
userManager[key]
? async (args: ProcessResourceOwnerPasswordCredentialsArgs & never[]) => {
dispatch({
type: "NAVIGATOR_INIT",
method: key,
});
try {
return await userManager[key](args);
} catch (error) {
dispatch({ type: "ERROR", error: error as Error });
return null;
} finally {
dispatch({ type: "NAVIGATOR_CLOSE" });
}
}
: unsupportedEnvironment(key),
]),
) as Pick<UserManager, typeof navigatorKeys[number]>,
),
[userManager],
);
const didInitialize = React.useRef(false);
React.useEffect(() => {
if (!userManager || didInitialize.current) {
return;
}
didInitialize.current = true;
void (async (): Promise<void> => {
// sign-in
try {
let user: User | undefined | null = null;
// check if returning back from authority server
if (hasAuthParams() && !skipSigninCallback) {
user = await userManager.signinCallback();
onSigninCallback && await onSigninCallback(user);
}
user = !user ? await userManager.getUser() : user;
dispatch({ type: "INITIALISED", user });
} catch (error) {
dispatch({ type: "ERROR", error: signinError(error) });
}
// sign-out
try {
if (matchSignoutCallback && matchSignoutCallback(userManager.settings)) {
const resp = await userManager.signoutCallback();
onSignoutCallback && await onSignoutCallback(resp);
}
} catch (error) {
dispatch({ type: "ERROR", error: signoutError(error) });
}
})();
}, [userManager, skipSigninCallback, onSigninCallback, onSignoutCallback, matchSignoutCallback]);
// register to userManager events
React.useEffect(() => {
if (!userManager) return undefined;
// event UserLoaded (e.g. initial load, silent renew success)
const handleUserLoaded = (user: User) => {
dispatch({ type: "USER_LOADED", user });
};
userManager.events.addUserLoaded(handleUserLoaded);
// event UserUnloaded (e.g. userManager.removeUser)
const handleUserUnloaded = () => {
dispatch({ type: "USER_UNLOADED" });
};
userManager.events.addUserUnloaded(handleUserUnloaded);
// event UserSignedOut (e.g. user was signed out in background (checkSessionIFrame option))
const handleUserSignedOut = () => {
dispatch({ type: "USER_SIGNED_OUT" });
};
userManager.events.addUserSignedOut(handleUserSignedOut);
// event SilentRenewError (silent renew error)
const handleSilentRenewError = (error: Error) => {
dispatch({ type: "ERROR", error });
};
userManager.events.addSilentRenewError(handleSilentRenewError);
return () => {
userManager.events.removeUserLoaded(handleUserLoaded);
userManager.events.removeUserUnloaded(handleUserUnloaded);
userManager.events.removeUserSignedOut(handleUserSignedOut);
userManager.events.removeSilentRenewError(handleSilentRenewError);
};
}, [userManager]);
const removeUser = React.useCallback(async () => {
if (!userManager) unsupportedEnvironment("removeUser");
await userManager.removeUser();
onRemoveUser && await onRemoveUser();
}, [userManager, onRemoveUser]);
const contextValue = React.useMemo(() => {
return {
...state,
...userManagerContext,
removeUser,
};
}, [state, userManagerContext, removeUser]);
return (
<AuthContext.Provider value={contextValue}>
{children}
</AuthContext.Provider>
);
};