forked from EddieHubCommunity/BioDrop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
56 lines (48 loc) · 1.42 KB
/
middleware.js
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
import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";
export const config = {
matcher: [
// account management
"/account/:path*",
"/api/account/:path*",
// admin section
"/admin/:path*",
"/api/admin/:path*",
],
};
export async function middleware(req) {
const sessionRequired = ["/account", "/api/account"];
const adminRequired = ["/admin", "/api/admin"];
const adminUsers = process.env.ADMIN_USERS.split(",");
const reqPathName = req.nextUrl.pathname;
// if not in sessionRequired or adminRequired, skip
if (
!sessionRequired
.concat(adminRequired)
.some((path) => reqPathName.startsWith(path))
) {
return NextResponse.next();
}
const session = await getToken({
req: req,
secret: process.env.NEXTAUTH_SECRET,
});
// if no session reject request
if (!session) {
if (reqPathName.startsWith("/api")) {
return NextResponse.json({}, { status: 401 });
}
return NextResponse.redirect(new URL("/auth/signin", req.url));
}
const username = session.username;
// if admin request check user is allowed
if (adminRequired.some((path) => reqPathName.startsWith(path))) {
if (!adminUsers.includes(username)) {
if (reqPathName.startsWith("/api")) {
return NextResponse.json({}, { status: 401 });
}
return NextResponse.redirect(new URL("/404", req.url));
}
}
return NextResponse.next();
}