-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
35 lines (29 loc) · 1 KB
/
Copy pathmiddleware.js
File metadata and controls
35 lines (29 loc) · 1 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
import { NextResponse } from 'next/server';
import { verifyJWT } from './lib/utils/server';
import CryptoJS from 'crypto-js';
export async function middleware(request) {
const path = request.nextUrl.pathname;
const access_key =
request.cookies.get(process.env.NEXT_PUBLIC_PREFIX_KEY + '-token')?.value ||
undefined;
if (path.startsWith('/admin') && !access_key) {
return NextResponse.redirect(new URL('/', request.nextUrl));
} else if (path.startsWith('/admin') && access_key) {
try {
const token = CryptoJS.AES.decrypt(
access_key,
process.env.CRYPTO_SECRET
).toString(CryptoJS.enc.Utf8);
await verifyJWT(token);
} catch (error) {
console.log(error);
return NextResponse.redirect(new URL('/invalid-auth', request.nextUrl));
}
}
if (path == '/' && access_key) {
return NextResponse.redirect(new URL('/admin/dashboard', request.nextUrl));
}
}
export const config = {
matcher: ['/', '/:path*'],
};