-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
49 lines (41 loc) · 1.26 KB
/
middleware.ts
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
import "server-only";
import { BASE_URL, getSession } from "@/utils/server";
import { NextRequest, NextResponse } from "next/server";
import { APIPathname } from "./enums";
async function validateUserSession(sessionToken: string) {
try {
const response = await fetch(BASE_URL + APIPathname.USER_VALIDATE, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${sessionToken}`,
},
});
if (!response.ok) {
throw new Error(`API call failed with status: ${response.status}`);
}
const data = await response.json();
return data.isValid;
} catch (error) {
return false;
}
}
export async function middleware(request: NextRequest) {
const sessionToken = await getSession("jwt");
if (sessionToken) {
try {
const isValidSession = await validateUserSession(sessionToken);
if (!isValidSession) {
return NextResponse.redirect(new URL(APIPathname.HOME, request.url));
}
} catch (error) {
return NextResponse.redirect(new URL(APIPathname.HOME, request.url));
}
} else {
return NextResponse.redirect(new URL(APIPathname.HOME, request.url));
}
return NextResponse.next();
}
export const config = {
matcher: "/dashboard(.*)",
};