-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
40 lines (31 loc) · 1.01 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import * as jose from 'jose';
const secret = process.env.NEXT_PUBLIC_SECRET;
export default async function middleware(req: NextRequest) {
const { cookies, nextUrl } = req;
const jwt = cookies.get('affilERP');
const loginUrl = nextUrl.clone();
loginUrl.pathname = '/auth/login';
if (nextUrl.pathname.startsWith('/protected')) {
if (jwt === undefined) {
return NextResponse.redirect(loginUrl);
}
try {
const { payload: jwtData } = await jose.jwtVerify(
jwt,
new TextEncoder().encode(secret)
);
if (jwtData) {
return NextResponse.next();
}
return NextResponse.redirect(loginUrl);
} catch (error) {
return NextResponse.redirect(loginUrl);
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/protected/:path*'],
};