-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
50 lines (43 loc) · 1.26 KB
/
middleware.js
File metadata and controls
50 lines (43 loc) · 1.26 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 { jwtVerify } from "jose";
export async function middleware(request) {
const token = request.cookies.get("auth_token");
const isAuthenticated = await verifyToken(token);
// Exclude auth routes
if (request.nextUrl.pathname.startsWith("/api/auth")) {
return NextResponse.next();
}
// Redirect login page by login status
if (request.nextUrl.pathname === "/login") {
return isAuthenticated
? NextResponse.redirect(new URL("/anime", request.url))
: NextResponse.next();
}
// If not logged in, return with different response
if (!isAuthenticated) {
return request.nextUrl.pathname.startsWith("/api")
? NextResponse.json({ code: 401, message: "Unauthorized", data: null }, { status: 401 })
: NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
async function verifyToken(token) {
if (!token) return false;
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
await jwtVerify(token.value, secret);
return true;
} catch (error) {
return false;
}
}
export const config = {
matcher: [
"/api/:path*",
"/anime",
"/anime/:path*",
"/downloads",
"/login",
"/settings/:path*",
],
}