-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
38 lines (28 loc) · 1.19 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
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
const requireAuth: string[] = ["/chat", "/api","/reporting", "/unauthorized"];
const requireAdmin: string[] = ["/reporting"];
export async function middleware(request: NextRequest) {
const res = NextResponse.next();
const pathname = request.nextUrl.pathname;
if (requireAuth.some((path) => pathname.startsWith(path))) {
const token = await getToken({
req: request
});
//check not logged in
if (!token) {
const url = new URL(`/`, request.url);
return NextResponse.redirect(url);
}
if (requireAdmin.some((path) => pathname.startsWith(path))) {
//check if not authorized
if (!token.isAdmin) {
const url = new URL(`/unauthorized`, request.url);
return NextResponse.rewrite(url);
}
}
}
return res;
}
// note that middleware is not applied to api/auth as this is required to logon (i.e. requires anon access)
export const config = { matcher: ["/chat/:path*", "/reporting/:path*", "/api/chat:path*"] };