-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
63 lines (52 loc) · 1.79 KB
/
middleware.ts
File metadata and controls
63 lines (52 loc) · 1.79 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
57
58
59
60
61
62
63
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';
import { getSessionSecret } from '@/lib/auth/session-secret';
const SESSION_COOKIE = 'qagent_session';
function getSessionKey(): Uint8Array {
return new TextEncoder().encode(getSessionSecret());
}
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
// Public paths that don't require auth
const publicPaths = ['/_next', '/api/auth', '/static', '/favicon.ico'];
// Allow public paths
if (publicPaths.some((p) => path.startsWith(p)) || path === '/') {
return NextResponse.next();
}
// Check if it's the dashboard or protected API
const isProtectedPath =
path.startsWith('/dashboard') || (path.startsWith('/api') && !path.startsWith('/api/auth'));
if (!isProtectedPath) {
return NextResponse.next();
}
const sessionToken = request.cookies.get(SESSION_COOKIE)?.value;
if (!sessionToken) {
if (path.startsWith('/api')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
} else {
return NextResponse.redirect(new URL('/', request.url));
}
}
try {
await jwtVerify(sessionToken, getSessionKey(), { algorithms: ['HS256'] });
return NextResponse.next();
} catch {
if (path.startsWith('/api')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
} else {
return NextResponse.redirect(new URL('/', request.url));
}
}
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};