-
Notifications
You must be signed in to change notification settings - Fork 787
/
middleware.ts
72 lines (59 loc) · 1.71 KB
/
middleware.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
import micromatch from 'micromatch';
import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import env from './lib/env';
// Add routes that don't require authentication
const unAuthenticatedRoutes = [
'/api/hello',
'/api/health',
'/api/auth/**',
'/api/oauth/**',
'/api/scim/v2.0/**',
'/api/invitations/*',
'/api/webhooks/stripe',
'/api/webhooks/dsync',
'/auth/**',
'/invitations/*',
'/terms-condition',
'/unlock-account',
'/login/saml',
'/.well-known/*',
];
export default async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Bypass routes that don't require authentication
if (micromatch.isMatch(pathname, unAuthenticatedRoutes)) {
return NextResponse.next();
}
const redirectUrl = new URL('/auth/login', req.url);
redirectUrl.searchParams.set('callbackUrl', encodeURI(req.url));
// JWT strategy
if (env.nextAuth.sessionStrategy === 'jwt') {
const token = await getToken({
req,
});
if (!token) {
return NextResponse.redirect(redirectUrl);
}
}
// Database strategy
else if (env.nextAuth.sessionStrategy === 'database') {
const url = new URL('/api/auth/session', req.url);
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
cookie: req.headers.get('cookie') || '',
},
});
const session = await response.json();
if (!session.user) {
return NextResponse.redirect(redirectUrl);
}
}
// All good, let the request through
return NextResponse.next();
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|api/auth/session).*)'],
};