-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathmiddleware.ts
55 lines (45 loc) · 1.5 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
import { createClient } from "@/lib/supabase/middleware"
import { NextResponse, type NextRequest } from "next/server"
export async function middleware(request: NextRequest) {
try {
const { supabase, response } = createClient(request)
const { data: { user } } = await supabase.auth.getUser()
if (user) {
// Use the same check_mfa() function as RLS policies
const { data: mfaCheck, error: mfaError } = await supabase
.rpc('check_mfa')
if (mfaError) throw mfaError
// If MFA check fails and we're not already on the verify page
if (!mfaCheck && !request.nextUrl.pathname.startsWith('/login/verify')) {
return NextResponse.redirect(
new URL('/login/verify', request.url))
}
// Handle root path redirect to user's home workspace
const redirectToChat = request.nextUrl.pathname === "/"
if (redirectToChat) {
const { data: homeWorkspace, error } = await supabase
.from("workspaces")
.select("*")
.eq("user_id", user.id)
.eq("is_home", true)
.single()
if (!homeWorkspace) {
throw new Error(error?.message)
}
return NextResponse.redirect(
new URL(`/${homeWorkspace.id}/chat`, request.url)
)
}
}
return response
} catch (e) {
return NextResponse.next({
request: {
headers: request.headers
}
})
}
}
export const config = {
matcher: "/((?!api|static|.*\\..*|_next|auth).*)"
}