forked from mckaywrigley/chatbot-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
61 lines (48 loc) · 1.68 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
58
59
60
61
import { createClient } from "@/lib/supabase/middleware"
import { NextResponse, type NextRequest } from "next/server"
import { msalInstance } from '@/lib/msal/msalConfig';
import Cookies from 'universal-cookie';
export async function middleware(request: NextRequest) {
try {
const { supabase, response } = createClient(request)
const session = await supabase.auth.getSession()
const redirectToChat = session && request.nextUrl.pathname === "/"
if (redirectToChat) {
const { data: homeWorkspace, error } = await supabase
.from("workspaces")
.select("*")
.eq("user_id", session.data.session?.user.id)
.eq("is_home", true)
.single()
if (!homeWorkspace) {
throw new Error(error?.message)
}
return NextResponse.redirect(
new URL(`/${homeWorkspace.id}/chat`, request.url)
)
}
// MSAL Authentication Logic
// Retrieve MSAL account from cookies
const cookies = new Cookies(request.headers.get('cookie'));
const msalAccountCookie = cookies.get('msalAccount');
const msalAccount = msalAccountCookie ? JSON.parse(msalAccountCookie) : null;
// If the user is authenticated, allow access to the /login page
if (request.nextUrl.pathname === "/login" && msalAccount) {
return NextResponse.next();
}
else if (request.nextUrl.pathname === "/login" && !msalAccount)
{
return NextResponse.rewrite(new URL('/error', request.url));
}
return response;
} catch (e) {
return NextResponse.next({
request: {
headers: request.headers
}
})
}
}
export const config = {
matcher: "/((?!api|static|.*\\..*|_next|auth).*)"
}