45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
import { clerkMiddleware, createRouteMatcher, clerkClient } from '@clerk/astro/server';
|
|
|
|
const isProtectedRoute = createRouteMatcher(['/pokemon']);
|
|
const isAdminRoute = createRouteMatcher(['/admin']);
|
|
|
|
const TARGET_ORG_ID = "org_3Baav9czkRLLlC7g89oJWqRRulK";
|
|
|
|
export const onRequest = clerkMiddleware(async (auth, context) => {
|
|
const { isAuthenticated, userId, redirectToSignIn } = auth();
|
|
|
|
if (!isAuthenticated && isProtectedRoute(context.request)) {
|
|
return redirectToSignIn();
|
|
}
|
|
|
|
if (isAdminRoute(context.request)) {
|
|
if (!isAuthenticated || !userId) {
|
|
return redirectToSignIn();
|
|
}
|
|
|
|
try {
|
|
const client = await clerkClient(context); // pass context here
|
|
const memberships = await client.organizations.getOrganizationMembershipList({
|
|
organizationId: TARGET_ORG_ID,
|
|
});
|
|
|
|
console.log("Total memberships found:", memberships.data.length);
|
|
console.log("Current userId:", userId);
|
|
console.log("Memberships:", JSON.stringify(memberships.data.map(m => ({
|
|
userId: m.publicUserData?.userId,
|
|
role: m.role,
|
|
})), null, 2));
|
|
|
|
const userMembership = memberships.data.find(
|
|
(m) => m.publicUserData?.userId === userId
|
|
);
|
|
|
|
if (!userMembership || userMembership.role !== "org:admin") {
|
|
return context.redirect("/");
|
|
}
|
|
} catch (e) {
|
|
console.error("Clerk membership check failed:", e);
|
|
return context.redirect("/");
|
|
}
|
|
}
|
|
}); |