-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathmiddleware.ts
More file actions
52 lines (41 loc) · 1.7 KB
/
Copy pathmiddleware.ts
File metadata and controls
52 lines (41 loc) · 1.7 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';
// Define paths that require authentication
const PROTECTED_ROUTES = ['/dashboard', '/portfolio', '/settings', '/invest'];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if the current path is a protected route
const isProtectedRoute = PROTECTED_ROUTES.some(route => pathname.startsWith(route));
if (isProtectedRoute) {
// Look for the auth token in cookies
const token = request.cookies.get('auth-token')?.value;
if (!token) {
// Redirect to home or login page if no token is found
const loginUrl = new URL('/', request.url);
loginUrl.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(loginUrl);
}
try {
// Ensure AUTH_SECRET is set in .env
const secretKey = process.env.AUTH_SECRET || 'default-fallback-secret-for-dev-only-do-not-use-in-prod';
const secret = new TextEncoder().encode(secretKey);
// Verify signature and expiry with 15s clock tolerance
await jwtVerify(token, secret, {
clockTolerance: 15,
});
} catch (error) {
// Token is invalid, expired, or tampered with
const loginUrl = new URL('/', request.url);
loginUrl.searchParams.set('callbackUrl', pathname);
const response = NextResponse.redirect(loginUrl);
// Clear the invalid cookie
response.cookies.delete('auth-token');
return response;
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/portfolio/:path*', '/settings/:path*', '/invest/:path*'],
};