-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
50 lines (41 loc) · 1.51 KB
/
middleware.ts
File metadata and controls
50 lines (41 loc) · 1.51 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { verifyJwt } from "./lib/auth";
export async function middleware(request: NextRequest) {
const token = request.cookies.get("auth-token")?.value;
// Paths that require authentication
const protectedPaths = ["/extract-marks", "/student-results"];
const isProtectedPath = protectedPaths.some((path) =>
request.nextUrl.pathname.startsWith(path),
);
if (isProtectedPath) {
if (!token) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("from", request.nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
const payload = await verifyJwt(token);
if (!payload) {
// Invalid token, clear cookie and redirect
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("from", request.nextUrl.pathname);
const response = NextResponse.redirect(loginUrl);
response.cookies.delete("auth-token");
return response;
}
}
// Prevent authenticated users from visiting auth pages
const isAuthPage =
request.nextUrl.pathname.startsWith("/login") ||
request.nextUrl.pathname.startsWith("/signup");
if (isAuthPage && token) {
const payload = await verifyJwt(token);
if (payload) {
return NextResponse.redirect(new URL("/student-results", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};