-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware.ts
57 lines (49 loc) · 1.46 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
50
51
52
53
54
55
56
57
import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
const { AUTH_SECRET } = process.env;
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const authCookiesName =
process.env.NODE_ENV === "production"
? "__Secure-authjs.session-token"
: "authjs.session-token";
const token = await getToken({
req,
secret: AUTH_SECRET,
cookieName: authCookiesName,
});
const protectedPaths = [
"/playlist/liked-songs",
"/playlist/user-playlist",
"/api/users",
];
const userPaths = [
`/api/users/${token?.sub}`,
"/api/users/public-playlist",
"/playlist/liked-songs",
"/playlist/user-playlist",
"/playlist",
];
if (!token) {
if (protectedPaths.some((path) => pathname.startsWith(path))) {
if (pathname.startsWith("/api/users")) {
return NextResponse.json({ error: "Unauthorized!" }, { status: 401 });
}
return NextResponse.redirect(new URL("/login", req.url));
}
} else {
if (pathname === "/login" || pathname === "/signup") {
return NextResponse.redirect(new URL("/", req.url));
}
if (!userPaths.some((path) => pathname.startsWith(path))) {
return NextResponse.json(
{ error: "You do not have access" },
{ status: 403 }
);
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/playlist/:path*", "/api/users/:path*", "/login", "/signup"],
};