-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathauthMiddleware.ts
More file actions
368 lines (325 loc) · 11.2 KB
/
authMiddleware.ts
File metadata and controls
368 lines (325 loc) · 11.2 KB
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
361
362
363
364
365
366
367
368
import { NextResponse } from "next/server";
import { config, routes } from "../config/index";
import { KindeAccessToken, KindeIdToken } from "../types";
import { jwtDecoder } from "@kinde/jwt-decoder";
import { isTokenExpired } from "../utils/jwt/validation";
import { getAccessToken } from "../utils/getAccessToken";
import { kindeClient } from "../session/kindeServerClient";
import { sessionManager } from "../session/sessionManager";
import { getSplitCookies } from "../utils/cookies/getSplitSerializedCookies";
import { getIdToken } from "../utils/getIdToken";
import { OAuth2CodeExchangeResponse } from "@kinde-oss/kinde-typescript-sdk";
import { copyCookiesToRequest } from "../utils/copyCookiesToRequest";
import { getStandardCookieOptions } from "../utils/cookies/getStandardCookieOptions";
import { isPublicPathMatch } from "../utils/isPublicPathMatch";
/**
* Handles invitation code redirect logic.
* Redirects to the register page with the invitation code, or to login on error.
*/
const handleInvitationCodeRedirect = (
req,
invitationCode: string,
registerPage: string,
loginRedirectUrl: string,
redirectURLBase: string | undefined,
): NextResponse => {
const method = req.method?.toUpperCase() ?? "GET";
if (method !== "GET" && method !== "HEAD") {
return NextResponse.json({ statusCode: 401, message: "Unauthorized" });
}
try {
const params = new URLSearchParams();
params.set("invitation_code", invitationCode);
params.set("is_invitation", "true");
const registerWithInviteRedirectUrl = `${registerPage}?${params.toString()}`;
return NextResponse.redirect(
new URL(
registerWithInviteRedirectUrl,
redirectURLBase || config.redirectURL,
),
);
} catch (error) {
if (config.isDebugMode) {
console.error(
"authMiddleware: error redirecting to register with invitation code",
error,
);
}
return NextResponse.redirect(
new URL(loginRedirectUrl, redirectURLBase || config.redirectURL),
);
}
};
const loginRedirect = (
req,
loginRedirectUrl: string,
redirectURLBase: string | undefined,
): NextResponse => {
const method = req.method?.toUpperCase() ?? "GET";
if (method !== "GET" && method !== "HEAD") {
return NextResponse.json({ statusCode: 401, message: "Unauthorized" });
}
return NextResponse.redirect(
new URL(loginRedirectUrl, redirectURLBase || config.redirectURL),
);
};
const handleMiddleware = async (req, options, onSuccess) => {
const { pathname, search } = req.nextUrl;
const params = new URLSearchParams(search);
const invitationCode = params.get("invitation_code");
const hasInvitationCode = !!invitationCode?.trim();
const isReturnToCurrentPage = options?.isReturnToCurrentPage;
const orgCode: string | undefined = options?.orgCode;
const loginPage = options?.loginPage || `${config.apiPath}/${routes.login}`;
const callbackPage = `${config.apiPath}/kinde_callback`;
const registerPage = `${config.apiPath}/${routes.register}`;
const setupPage = `${config.apiPath}/${routes.setup}`;
if (
loginPage == pathname ||
callbackPage == pathname ||
registerPage == pathname ||
setupPage == pathname
) {
return NextResponse.next();
}
let publicPaths = ["/_next", "/favicon.ico"];
if (options?.publicPaths !== undefined) {
if (Array.isArray(options?.publicPaths)) {
publicPaths = options.publicPaths;
}
}
const loginRedirectUrlParams = new URLSearchParams();
if (orgCode) {
loginRedirectUrlParams.set("org_code", orgCode);
}
if (isReturnToCurrentPage) {
loginRedirectUrlParams.set("post_login_redirect_url", pathname + search);
}
const queryString = loginRedirectUrlParams.toString();
const loginRedirectUrl = queryString
? `${loginPage}?${queryString}`
: loginPage;
if (hasInvitationCode) {
return handleInvitationCodeRedirect(
req,
invitationCode,
registerPage,
loginRedirectUrl,
options?.redirectURLBase,
);
}
// Use extracted utility for public path matching
// eslint-disable-next-line @typescript-eslint/no-var-requires
const isPublicPath = isPublicPathMatch(
pathname,
publicPaths,
config.isDebugMode,
);
// getAccessToken will validate the token
let kindeAccessToken = await getAccessToken(req);
// getIdToken will validate the token
let kindeIdToken = await getIdToken(req);
// if no access token, redirect to login
if ((!kindeAccessToken || !kindeIdToken) && !isPublicPath) {
if (config.isDebugMode) {
console.log(
"authMiddleware: no access or id token, redirecting to login",
);
}
return loginRedirect(req, loginRedirectUrl, options?.redirectURLBase);
}
const session = await sessionManager(req);
let refreshResponse: OAuth2CodeExchangeResponse | null = null;
const resp = NextResponse.next();
// if accessToken is expired, refresh it
if (
isTokenExpired(kindeAccessToken, 20) ||
isTokenExpired(kindeIdToken, 20)
) {
if (config.isDebugMode) {
console.log("authMiddleware: access token expired, refreshing");
}
const sendResult = (debugMessage: string): NextResponse | undefined => {
if (config.isDebugMode) {
console.error(debugMessage);
}
if (!isPublicPath) {
return loginRedirect(req, loginRedirectUrl, options?.redirectURLBase);
}
return undefined;
};
try {
refreshResponse = await kindeClient.refreshTokens(session, false);
kindeAccessToken = refreshResponse.access_token;
kindeIdToken = refreshResponse.id_token;
if (config.isDebugMode) {
console.log(
"authMiddleware: tokens refreshed",
!!refreshResponse.access_token,
!!refreshResponse.id_token,
);
}
} catch (error) {
const result = sendResult("authMiddleware: error refreshing tokens");
if (result) return result;
}
try {
let persistent = true;
const payload: { ksp?: { persistent: boolean } } | null = jwtDecoder<{
ksp: { persistent: boolean };
}>(refreshResponse.access_token);
if (payload) {
persistent = payload.ksp?.persistent ?? true;
}
// if we want layouts/pages to get immediate access to the new token,
// we need to set the cookie on the response here
const splitAccessTokenCookies = getSplitCookies(
"access_token",
refreshResponse.access_token,
);
splitAccessTokenCookies.forEach((cookie) => {
if (!persistent) {
delete cookie.options.maxAge;
}
resp.cookies.set(cookie.name, cookie.value, cookie.options);
});
const splitIdTokenCookies = getSplitCookies(
"id_token",
refreshResponse.id_token,
);
splitIdTokenCookies.forEach((cookie) => {
if (!persistent) {
delete cookie.options.maxAge;
}
resp.cookies.set(cookie.name, cookie.value, cookie.options);
});
const standardCookieOptions = getStandardCookieOptions();
if (!persistent) {
delete standardCookieOptions.maxAge;
}
resp.cookies.set(
"refresh_token",
refreshResponse.refresh_token,
standardCookieOptions,
);
// copy the cookies from the response to the request
// in Next versions prior to 14.2.8, the cookies function
// reads the Set-Cookie header from the *request* object, not the *response* object
// in order to get the new cookies to the request, we need to copy them over
copyCookiesToRequest(req, resp);
if (config.isDebugMode) {
console.log("authMiddleware: tokens refreshed and cookies updated");
}
} catch (error) {
const result = sendResult(
"authMiddleware: error settings new token in cookie",
);
if (result) return result;
}
}
// we don't bail out earlier than here because we want to refresh the tokens
// if they are expired, even if the path is public
if (isPublicPath) {
return resp;
}
let accessTokenValue: KindeAccessToken | null = null;
let idTokenValue: KindeIdToken | null = null;
try {
accessTokenValue = jwtDecoder<KindeAccessToken>(kindeAccessToken);
} catch (error) {
if (config.isDebugMode) {
console.error(
"authMiddleware: access token decode failed, redirecting to login",
);
}
return loginRedirect(req, loginRedirectUrl, options?.redirectURLBase);
}
try {
idTokenValue = jwtDecoder<KindeIdToken>(kindeIdToken);
} catch (error) {
if (config.isDebugMode) {
console.error(
"authMiddleware: id token decode failed, redirecting to login",
);
}
return loginRedirect(req, loginRedirectUrl, options?.redirectURLBase);
}
const customValidationValid = options?.isAuthorized
? options.isAuthorized({ req, token: accessTokenValue })
: true;
if (customValidationValid && onSuccess) {
if (config.isDebugMode) {
console.log("authMiddleware: invoking onSuccess callback");
}
const callbackResult = await onSuccess({
token: accessTokenValue,
user: {
family_name: idTokenValue.family_name,
given_name: idTokenValue.given_name,
email: idTokenValue.email,
id: idTokenValue.sub,
picture: idTokenValue.picture,
},
});
// If a user returned a response from their onSuccess callback, copy our refreshed tokens to it
if (callbackResult instanceof NextResponse) {
if (config.isDebugMode) {
console.log(
"authMiddleware: onSuccess callback returned a response, copying our cookies to it",
);
}
// Copy our cookies to their response
resp.cookies.getAll().forEach((cookie) => {
callbackResult.cookies.set(cookie.name, cookie.value, {
...cookie,
});
});
copyCookiesToRequest(req, callbackResult);
return callbackResult;
}
// If they didn't return a response, return our response with the refreshed tokens
if (config.isDebugMode) {
console.log(
"authMiddleware: onSuccess callback did not return a response, returning our response",
);
}
return resp;
}
if (customValidationValid) {
if (config.isDebugMode) {
console.log(
"authMiddleware: customValidationValid is true, returning response",
);
}
return resp;
}
if (config.isDebugMode) {
console.log("authMiddleware: default behaviour, redirecting to login");
}
return loginRedirect(req, loginRedirectUrl, options?.redirectURLBase);
};
/**
* @param {Request} [req]
* @param {function(req: Request & {kindeAuth: {user: any, token: string}})} [onIsAuthorized]
*/
export function withAuth(...args) {
// most basic usage - no options
if (!args.length || args[0] instanceof Request) {
// @ts-ignore
return handleMiddleware(...args);
}
// passing through the kindeAuth data to the middleware function
if (typeof args[0] === "function") {
const middleware = args[0];
const options = args[1];
return async (...args) =>
await handleMiddleware(args[0], options, async ({ token, user }) => {
args[0].kindeAuth = { token, user };
return await middleware(...args);
});
}
// includes options
const options = args[0];
// @ts-ignore
return async (...args) => await handleMiddleware(args[0], options);
}