-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
35 lines (31 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
import { NextResponse } from 'next/server'
import { NextRequest } from 'next/server'
import { jwtVerify } from "jose";
import { JWTExpired } from "jose/errors";
export async function middleware(request: NextRequest) {
if (request.nextUrl.pathname === "/about") {
return NextResponse.redirect(new URL("/", request.url), { status: 301 });
}
const token = request.cookies.get("token")
if (request.nextUrl.pathname === "/new" || request.nextUrl.searchParams.get("edit") === "true") {
if (!token) {
return NextResponse.redirect(new URL("/no-access", request.url));
}
try {
const decoded = await jwtVerify(token.value, new TextEncoder().encode(process.env.SECRET_KEY as string));
if (decoded.payload.role === "admin") {
return NextResponse.next()
} else {
return NextResponse.redirect(new URL("/no-access", request.url));
}
} catch (error) {
if (error instanceof JWTExpired) {
return NextResponse.redirect(new URL("/?expired=true", request.url));
}
return NextResponse.redirect(new URL("/no-access", request.url));
}
}
if (token && request.nextUrl.pathname === "/login") {
return NextResponse.redirect(new URL("/", request.url));
}
}