-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
30 lines (24 loc) · 810 Bytes
/
middleware.ts
File metadata and controls
30 lines (24 loc) · 810 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
// middleware.ts
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
// Load allowed users from the environment variables
const allowedUsers = process.env.ALLOWED_USERS?.split(",") || [];
export default withAuth(function middleware(req) {
const { pathname, origin } = req.nextUrl;
if (pathname.startsWith("/admin")) {
const token = req.nextauth.token;
// Check if the user ID is allowed to access
if (
!token ||
typeof token.id !== "number" ||
!allowedUsers.includes(token.id.toString())
) {
const signInUrl = new URL("/auth/signin", origin);
signInUrl.searchParams.set("callbackUrl", req.url);
return NextResponse.redirect(signInUrl);
}
}
});
export const config = {
matcher: ["/admin/:path*"],
};