forked from microsoft/azurechat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
50 lines (43 loc) · 1.18 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
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
const requireAuth: string[] = [
"/chat",
"/api",
"/reporting",
"/unauthorized",
"/persona",
"/prompt"
];
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: [
"/unauthorized/:path*",
"/reporting/:path*",
"/api/chat:path*",
"/api/images:path*",
"/chat/:path*",
],
};