-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathprofile.ts
241 lines (211 loc) · 6.6 KB
/
profile.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
import { NextApiResponse, NextApiRequest } from 'next';
import { NextRequest, NextResponse } from 'next/server';
import { ClientFactory } from '../auth0-session';
import { SessionCache, Session, fromJson, GetAccessToken } from '../session';
import { assertReqRes } from '../utils/assert';
import { ProfileHandlerError, HandlerErrorCause } from '../utils/errors';
import { AppRouteHandlerFnContext, AuthHandler, getHandler, Handler, OptionsProvider } from './router-helpers';
/**
* After refetch handler for page router {@link AfterRefetchPageRoute} and app router {@link AfterRefetchAppRoute}.
*
* @category Server
*/
export type AfterRefetch = AfterRefetchPageRoute | AfterRefetchAppRoute;
/**
* After refetch handler for page router.
*
* @category Server
*/
export type AfterRefetchPageRoute = (
req: NextApiRequest,
res: NextApiResponse,
session: Session
) => Promise<Session> | Session;
/**
* After refetch handler for app router.
*
* @category Server
*/
export type AfterRefetchAppRoute = (req: NextRequest, session: Session) => Promise<Session> | Session;
/**
* Options to customize the profile handler.
*
* @see {@link HandleProfile}
*
* @category Server
*/
export type ProfileOptions = {
/**
* If set to `true` this will refetch the user profile information from `/userinfo` and save it
* to the session.
*/
refetch?: boolean;
/**
* Like {@link AfterCallback} and {@link AfterRefresh} when a session is created, you can use
* this function to validate or add/remove claims after the session is updated. Will only run if
* {@link ProfileOptions.refetch} is `true`.
*/
afterRefetch?: AfterRefetch;
};
/**
* Options provider for the default profile handler.
* Use this to generate options that depend on values from the request.
*
* @category Server
*/
export type ProfileOptionsProvider = OptionsProvider<ProfileOptions>;
/**
* Use this to customize the default profile 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, handleProfile } from '@auth0/nextjs-auth0';
*
* export default handleAuth({
* profile: handleProfile({ refetch: true })
* });
* ```
*
* @example Pass a function that receives the request and returns an options object
*
* ```js
* // pages/api/auth/[auth0].js
* import { handleAuth, handleProfile } from '@auth0/nextjs-auth0';
*
* export default handleAuth({
* profile: handleProfile((req) => {
* return { refetch: true };
* })
* });
* ```
*
* This is useful for generating options that depend on values from the request.
*
* @example Override the profile handler
*
* ```js
* import { handleAuth, handleProfile } from '@auth0/nextjs-auth0';
*
* export default handleAuth({
* profile: async (req, res) => {
* try {
* await handleProfile(req, res, { refetch: true });
* } catch (error) {
* console.error(error);
* }
* }
* });
* ```
*
* @category Server
*/
export type HandleProfile = AuthHandler<ProfileOptions>;
/**
* The handler for the `/api/auth/me` API route.
*
* @throws {@link HandlerError}
*
* @category Server
*/
export type ProfileHandler = Handler<ProfileOptions>;
/**
* @ignore
*/
export default function profileHandler(
getClient: ClientFactory,
getAccessToken: GetAccessToken,
sessionCache: SessionCache
): HandleProfile {
const appRouteHandler = appRouteHandlerFactory(getClient, getAccessToken, sessionCache);
const pageRouteHandler = pageRouteHandlerFactory(getClient, getAccessToken, sessionCache);
return getHandler<ProfileOptions>(appRouteHandler, pageRouteHandler) as HandleProfile;
}
/**
* @ignore
*/
const appRouteHandlerFactory: (
getClient: ClientFactory,
getAccessToken: GetAccessToken,
sessionCache: SessionCache
) => (req: NextRequest, ctx: AppRouteHandlerFnContext, options?: ProfileOptions) => Promise<Response> | Response =
(getClient, getAccessToken, sessionCache) =>
async (req, _ctx, options = {}) => {
try {
const res = new NextResponse();
if (!(await sessionCache.isAuthenticated(req, res))) {
return new Response(null, { status: 204 });
}
const session = (await sessionCache.get(req, res)) as Session;
res.headers.set('Cache-Control', 'no-store');
if (options.refetch) {
const { accessToken } = await getAccessToken(req, res);
if (!accessToken) {
throw new Error('No access token available to refetch the profile');
}
const client = await getClient();
const userInfo = await client.userinfo(accessToken);
let newSession = fromJson({
...session,
user: {
...session.user,
...userInfo
}
}) as Session;
if (options.afterRefetch) {
newSession = await (options.afterRefetch as AfterRefetchAppRoute)(req, newSession);
}
await sessionCache.set(req, res, newSession);
return NextResponse.json(newSession.user, res);
}
return NextResponse.json(session.user, res);
} catch (e) {
throw new ProfileHandlerError(e as HandlerErrorCause);
}
};
/**
* @ignore
*/
const pageRouteHandlerFactory: (
getClient: ClientFactory,
getAccessToken: GetAccessToken,
sessionCache: SessionCache
) => (req: NextApiRequest, res: NextApiResponse, options?: ProfileOptions) => Promise<void> =
(getClient, getAccessToken, sessionCache) =>
async (req: NextApiRequest, res: NextApiResponse, options = {}): Promise<void> => {
try {
assertReqRes(req, res);
if (!(await sessionCache.isAuthenticated(req, res))) {
res.status(204).end();
return;
}
const session = (await sessionCache.get(req, res)) as Session;
res.setHeader('Cache-Control', 'no-store');
if (options.refetch) {
const { accessToken } = await getAccessToken(req, res);
if (!accessToken) {
throw new Error('No access token available to refetch the profile');
}
const client = await getClient();
const userInfo = await client.userinfo(accessToken);
let newSession = fromJson({
...session,
user: {
...session.user,
...userInfo
}
}) as Session;
if (options.afterRefetch) {
newSession = await (options.afterRefetch as AfterRefetchPageRoute)(req, res, newSession);
}
await sessionCache.set(req, res, newSession);
res.json(newSession.user);
return;
}
res.json(session.user);
} catch (e) {
throw new ProfileHandlerError(e as HandlerErrorCause);
}
};