-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
42 lines (34 loc) · 1.24 KB
/
middleware.ts
File metadata and controls
42 lines (34 loc) · 1.24 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { decrypt } from './lib/jwt';
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Protect /admin routes and /api/admin routes
if (pathname.startsWith('/admin') || pathname.startsWith('/api/admin')) {
// Exclude login page
if (pathname === '/admin/login') {
return NextResponse.next();
}
const session = request.cookies.get('session')?.value;
const unauthorizedResponse = () => {
if (pathname.startsWith('/api/') || pathname.includes('/api/admin')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.redirect(new URL('/admin/login', request.url));
};
if (!session) {
return unauthorizedResponse();
}
try {
await decrypt(session);
return NextResponse.next();
} catch (error) {
// Invalid session
return unauthorizedResponse();
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/admin/:path*', '/api/admin/:path*'],
};