-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathcallback.ts
360 lines (345 loc) · 9.95 KB
/
callback.ts
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import { strict as assert } from 'assert';
import { NextApiResponse, NextApiRequest } from 'next';
import { NextRequest, NextResponse } from 'next/server';
import {
AuthorizationParameters,
HandleCallback as BaseHandleCallback,
AfterCallback as BaseAfterCallback,
HandleLogin as BaseHandleLogin
} from '../auth0-session';
import { Session } from '../session';
import { assertReqRes } from '../utils/assert';
import { BaseConfig, NextConfig } from '../config';
import { CallbackHandlerError, HandlerErrorCause } from '../utils/errors';
import { Auth0NextApiRequest, Auth0NextApiResponse, Auth0NextRequest, Auth0NextResponse } from '../http';
import { LoginOptions } from './login';
import { AppRouteHandlerFnContext, AuthHandler, getHandler, Handler, OptionsProvider } from './router-helpers';
/**
* afterCallback hook for page router {@link AfterCallbackPageRoute} and app router {@link AfterCallbackAppRoute}
*/
export type AfterCallback = AfterCallbackPageRoute | AfterCallbackAppRoute;
/**
* Use this function for validating additional claims on the user's ID token or adding removing items from
* the session after login.
*
* @example Validate additional claims
*
* ```js
* // pages/api/auth/[auth0].js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
*
* const afterCallback = (req, res, session, state) => {
* if (session.user.isAdmin) {
* return session;
* } else {
* res.status(401).end('User is not admin');
* }
* };
*
* export default handleAuth({
* async callback(req, res) {
* try {
* await handleCallback(req, res, { afterCallback });
* } catch (error) {
* res.status(error.status || 500).end();
* }
* }
* });
* ```
*
* @example Modify the session after login
*
* ```js
* // pages/api/auth/[auth0].js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
*
* const afterCallback = (req, res, session, state) => {
* session.user.customProperty = 'foo';
* delete session.refreshToken;
* return session;
* };
*
* export default handleAuth({
* async callback(req, res) {
* try {
* await handleCallback(req, res, { afterCallback });
* } catch (error) {
* res.status(error.status || 500).end();
* }
* }
* });
* ```
*
* @example Redirect successful login based on claim
*
* ```js
* // pages/api/auth/[auth0].js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
*
* const afterCallback = (req, res, session, state) => {
* if (!session.user.isAdmin) {
* res.setHeader('Location', '/admin');
* }
* return session;
* };
*
* export default handleAuth({
* async callback(req, res) {
* try {
* await handleCallback(req, res, { afterCallback });
* } catch (error) {
* res.status(error.status || 500).end(error.message);
* }
* }
* });
* ```
*
* @throws {@link HandlerError}
*
* @category Server
*/
export type AfterCallbackPageRoute = (
req: NextApiRequest,
res: NextApiResponse,
session: Session,
state?: { [key: string]: any }
) => Promise<Session | undefined> | Session | undefined;
/**
* Use this function for validating additional claims on the user's ID token or adding removing items from
* the session after login.
*
* @example Validate additional claims
*
* ```js
* // app/api/auth/[auth0]/route.js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
* import { redirect } from 'next/navigation';
*
* const afterCallback = (req, session, state) => {
* if (session.user.isAdmin) {
* return session;
* } else {
* redirect('/unauthorized');
* }
* };
*
* export default handleAuth({
* callback: handleCallback({ afterCallback })
* });
* ```
*
* @example Modify the session after login
*
* ```js
* // pages/api/auth/[auth0].js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
* import { NextResponse } from 'next/server';
*
* const afterCallback = (req, session, state) => {
* session.user.customProperty = 'foo';
* delete session.refreshToken;
* return session;
* };
*
* export default handleAuth({
* callback: handleCallback({ afterCallback })
* });
* ```
*
* @example Redirect successful login based on claim
*
* ```js
* // pages/api/auth/[auth0].js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
* import { headers } from 'next/headers';
*
* const afterCallback = (req, session, state) => {
* if (!session.user.isAdmin) {
* headers.set('location', '/admin');
* }
* return session;
* };
*
* export default handleAuth({
* callback: handleCallback({ afterCallback })
* });
* ```
*
* @throws {@link HandlerError}
*
* @category Server
*/
export type AfterCallbackAppRoute = (
req: NextRequest,
session: Session,
state?: { [key: string]: any }
) => Promise<Session | Response | undefined> | Session | Response | undefined;
/**
* Options to customize the callback handler.
*
* @see {@link HandleCallback}
*
* @category Server
*/
export interface CallbackOptions {
afterCallback?: AfterCallback;
/**
* This is useful to specify in addition to {@link BaseConfig.baseURL} when your app runs on multiple domains,
* it should match {@link LoginOptions.authorizationParams.redirect_uri}.
*/
redirectUri?: string;
/**
* This is useful to specify instead of {@link NextConfig.organization} when your app has multiple
* organizations, it should match {@link LoginOptions.authorizationParams}.
*/
organization?: string;
/**
* This is useful for sending custom query parameters in the body of the code exchange request
* for use in Actions/Rules.
*/
authorizationParams?: Partial<AuthorizationParameters>;
}
/**
* Options provider for the default callback handler.
* Use this to generate options that depend on values from the request.
*
* @category Server
*/
export type CallbackOptionsProvider = OptionsProvider<CallbackOptions>;
/**
* Use this to customize the default callback handler without overriding it.
* You can still override the handler if needed.
*
* @example Pass an options object
*
* ```js
* // pages/api/auth/[auth0].js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
*
* export default handleAuth({
* callback: handleCallback({ redirectUri: 'https://example.com' })
* });
* ```
*
* @example Pass a function that receives the request and returns an options object
*
* ```js
* // pages/api/auth/[auth0].js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
*
* export default handleAuth({
* callback: handleCallback((req) => {
* return { redirectUri: 'https://example.com' };
* })
* });
* ```
*
* This is useful for generating options that depend on values from the request.
*
* @example Override the callback handler
*
* ```js
* import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
*
* export default handleAuth({
* callback: async (req, res) => {
* try {
* await handleCallback(req, res, {
* redirectUri: 'https://example.com'
* });
* } catch (error) {
* console.error(error);
* }
* }
* });
* ```
*
* @category Server
*/
export type HandleCallback = AuthHandler<CallbackOptions>;
/**
* The handler for the `/api/auth/callback` API route.
*
* @throws {@link HandlerError}
*
* @category Server
*/
export type CallbackHandler = Handler<CallbackOptions>;
/**
* @ignore
*/
export default function handleCallbackFactory(handler: BaseHandleCallback, config: NextConfig): HandleCallback {
const appRouteHandler = appRouteHandlerFactory(handler, config);
const pageRouteHandler = pageRouteHandlerFactory(handler, config);
return getHandler<CallbackOptions>(appRouteHandler, pageRouteHandler) as HandleCallback;
}
const applyOptions = (
req: NextApiRequest | NextRequest,
res: NextApiResponse | undefined,
options: CallbackOptions,
config: NextConfig
) => {
const opts = { ...options };
const idTokenValidator =
(afterCallback?: AfterCallback, organization?: string): BaseAfterCallback =>
(session, state) => {
if (organization) {
assert(session.user.org_id, 'Organization Id (org_id) claim must be a string present in the ID token');
assert.equal(
session.user.org_id,
organization,
`Organization Id (org_id) claim value mismatch in the ID token; ` +
`expected "${organization}", found "${session.user.org_id}"`
);
}
if (afterCallback) {
if (res) {
return (afterCallback as AfterCallbackPageRoute)(req as NextApiRequest, res, session, state);
} else {
return (afterCallback as AfterCallbackAppRoute)(req as NextRequest, session, state);
}
}
return session;
};
return {
...opts,
afterCallback: idTokenValidator(opts.afterCallback, opts.organization || config.organization)
};
};
/**
* @ignore
*/
const appRouteHandlerFactory: (
handler: BaseHandleLogin,
config: NextConfig
) => (req: NextRequest, ctx: AppRouteHandlerFnContext, options?: CallbackOptions) => Promise<Response> | Response =
(handler, config) =>
async (req, _ctx, options = {}) => {
try {
const auth0Res = new Auth0NextResponse(new NextResponse());
await handler(new Auth0NextRequest(req), auth0Res, applyOptions(req, undefined, options, config));
return auth0Res.res;
} catch (e) {
throw new CallbackHandlerError(e as HandlerErrorCause);
}
};
/**
* @ignore
*/
const pageRouteHandlerFactory: (
handler: BaseHandleCallback,
config: NextConfig
) => (req: NextApiRequest, res: NextApiResponse, options?: CallbackOptions) => Promise<void> =
(handler, config) =>
async (req: NextApiRequest, res: NextApiResponse, options = {}): Promise<void> => {
try {
assertReqRes(req, res);
return await handler(
new Auth0NextApiRequest(req),
new Auth0NextApiResponse(res),
applyOptions(req, res, options, config)
);
} catch (e) {
throw new CallbackHandlerError(e as HandlerErrorCause);
}
};