-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
46 lines (44 loc) · 1.33 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
"use server";
import { NextResponse } from "next/server";
import { jwtVerify, decodeJwt } from "jose";
import type { NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
const secret = new TextEncoder().encode(process.env.JWT_KEY as string);
try {
if (!request.url.includes("/sign-in")) {
const token = request.cookies.get("access_token");
if (token) {
if (!jwtVerify(token?.value, secret)) {
return NextResponse.redirect(
new URL("/sign-in?msg='JWT Expired.'", request.url)
);
}
const { isAdmin } = decodeJwt(token.value);
if (isAdmin) {
return NextResponse.next();
} else {
return NextResponse.redirect(
new URL("/?msg='Not Admin'", request.url)
);
}
} else {
return NextResponse.redirect(new URL("/admin/sign-in", request.url));
}
} else {
return NextResponse.next();
}
} catch (err) {
if (err instanceof Error && err.name === "JWTExpired") {
return NextResponse.redirect(
new URL("/sign-in?msg='Jwt Expired'", request.url)
);
}
return NextResponse.json(
{ message: "An unexpected error occurred." },
{ status: 500 }
);
}
}
export const config = {
matcher: ["/admin/:path*", "/admin"],
};