-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
42 lines (34 loc) · 1.04 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
import appConfig from '@/config/app';
import { User } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';
interface ResponseApi {
message?: string;
status: string;
code: number;
}
export const config = {
matcher: ['/dashboard', '/dashboard/:path*'],
};
export async function middleware(req: NextRequest) {
const sessionToken =
req.cookies.get('__Secure-next-auth.session-token') ??
req.cookies.get('next-auth.session-token');
if (!sessionToken) return redirect('/', req.url);
const userUrl = appConfig.api.sessions.user(sessionToken.value);
const user: (User & ResponseApi) | null = await (
await fetch(userUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Origin: appConfig.host,
},
credentials: 'same-origin',
})
).json();
if (!user) return redirect('/', req.url);
return NextResponse.next();
}
function redirect(path: string, url: string) {
const redirectUrl = new URL(path, url);
return NextResponse.redirect(redirectUrl);
}