-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
56 lines (44 loc) · 1.69 KB
/
middleware.ts
File metadata and controls
56 lines (44 loc) · 1.69 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
import { fetchAuthSession } from 'aws-amplify/auth/server';
import { NextRequest, NextResponse } from 'next/server';
import { createServerRunner } from '@aws-amplify/adapter-nextjs';
import outputs from '@/amplify_outputs.json';
const { runWithAmplifyServerContext } = createServerRunner({
config: outputs
});
export async function middleware(request: NextRequest) {
const response = NextResponse.next();
const authenticated = await runWithAmplifyServerContext({
nextServerContext: { request, response },
operation: async (contextSpec) => {
try {
const session = await fetchAuthSession(contextSpec);
return session.tokens !== undefined;
} catch (error) {
return false;
}
},
});
const isProtectedCustomerRoute = request.nextUrl.pathname.startsWith('/customer') &&
!request.nextUrl.pathname.startsWith('/customer/vehicles');
const isOnDashboard = isProtectedCustomerRoute ||
request.nextUrl.pathname.startsWith('/employee') ||
request.nextUrl.pathname.startsWith('/admin');
if (isOnDashboard && !authenticated) {
return NextResponse.redirect(new URL('/login', request.url));
}
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - login
* - signup
*/
'/((?!api|_next/static|_next/image|favicon.ico|login|signup|privacy-policy|data-deletion).*)',
],
};