-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
36 lines (29 loc) · 914 Bytes
/
middleware.ts
File metadata and controls
36 lines (29 loc) · 914 Bytes
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
import { NextRequest, NextResponse } from "next/server"
import { jwtVerify } from "jose"
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET)
export const COOKIE_NAME = "pmsession"
export async function middleware(req: NextRequest) {
const token = req.cookies.get(COOKIE_NAME)?.value
const isLogin = req.nextUrl.pathname === "/login"
let validToken = false
if (token) {
try {
await jwtVerify(token, JWT_SECRET)
validToken = true
} catch {
validToken = false
}
}
if (isLogin && validToken) {
return NextResponse.redirect(new URL("/", req.url))
}
if (!validToken && !isLogin && !req.nextUrl.pathname.startsWith("/api/")) {
return NextResponse.redirect(new URL("/login", req.url))
}
return NextResponse.next()
}
export const config = {
matcher: [
"/((?!api/ingest|api/login|login|favicon.svg|.*\\.js$|.*\\.css$|_next/).*)",
],
}