-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
96 lines (80 loc) · 2.45 KB
/
proxy.ts
File metadata and controls
96 lines (80 loc) · 2.45 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
const isPublicRoute = createRouteMatcher([
"/",
"/sign-in(.*)",
"/sign-up(.*)",
]);
export default clerkMiddleware(async (auth, req) => {
const { userId } = await auth();
const pathname = req.nextUrl.pathname;
////////////////////////////////////////
// CRITICAL FIX: BYPASS API ROUTES
////////////////////////////////////////
if (pathname.startsWith("/api")) {
return NextResponse.next();
}
////////////////////////////////////////
// NOT SIGNED IN (ONLY FOR PAGES)
////////////////////////////////////////
if (!userId && !isPublicRoute(req)) {
const signInUrl = new URL("/sign-in", req.url);
signInUrl.searchParams.set("redirect_url", pathname);
return NextResponse.redirect(signInUrl);
}
////////////////////////////////////////
// SIGNED IN
////////////////////////////////////////
if (userId) {
try {
const user = await prisma.user.findUnique({
where: { clerkUserId: userId },
select: {
role: true,
isOnboarded: true,
},
});
// USER NOT IN DB
if (!user && !pathname.startsWith("/post-auth")) {
return NextResponse.redirect(new URL("/post-auth", req.url));
}
// ROLE NOT CHOSEN
if (user && !user.role) {
if (!pathname.startsWith("/onboarding/role")) {
return NextResponse.redirect(
new URL("/onboarding/role", req.url)
);
}
}
// ONBOARDING NOT COMPLETE
if (user?.role && !user.isOnboarded) {
const onboardingPath =
user.role === "FARMER"
? "/onboarding/farmer"
: "/onboarding/landowner";
if (!pathname.startsWith(onboardingPath)) {
return NextResponse.redirect(
new URL(onboardingPath, req.url)
);
}
}
// FULLY ONBOARDED
if (user?.role && user.isOnboarded) {
const dashboard =
user.role === "FARMER"
? "/farmer/dashboard"
: "/landowner/dashboard";
if (pathname.startsWith("/onboarding")) {
return NextResponse.redirect(new URL(dashboard, req.url));
}
}
} catch (e) {
console.error("Middleware DB error:", e);
}
}
return NextResponse.next();
});
export const config = {
matcher: ["/((?!_next|.*\\..*).*)"],
};