Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion apps/api/src/app/api/electric/[...path]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ export async function GET(request: Request): Promise<Response> {
return new Response("Missing table parameter", { status: 400 });
}

const whereClause = await buildWhereClause(tableName, organizationId);
const whereClause = await buildWhereClause(
tableName,
organizationId,
sessionData.user.id,
);
if (!whereClause) {
return new Response(`Unknown table: ${tableName}`, { status: 400 });
}
Expand Down
22 changes: 4 additions & 18 deletions apps/api/src/app/api/electric/[...path]/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ function build(table: PgTable, column: PgColumn, id: string): WhereClause {
export async function buildWhereClause(
tableName: string,
organizationId: string,
userId: string,
): Promise<WhereClause | null> {
switch (tableName) {
case "tasks":
Expand All @@ -58,32 +59,17 @@ export async function buildWhereClause(
return build(invitations, invitations.organizationId, organizationId);

case "auth.organizations": {
// Use the authenticated user's ID to find their organizations
const userMemberships = await db.query.members.findMany({
where: eq(members.organizationId, organizationId),
columns: { userId: true },
});

if (userMemberships.length === 0) {
return { fragment: "1 = 0", params: [] };
}

const userId = userMemberships[0]?.userId;
if (!userId) {
return { fragment: "1 = 0", params: [] };
}

const allUserMemberships = await db.query.members.findMany({
where: eq(members.userId, userId),
columns: { organizationId: true },
});

if (allUserMemberships.length === 0) {
if (userMemberships.length === 0) {
return { fragment: "1 = 0", params: [] };
}

const orgIds = [
...new Set(allUserMemberships.map((m) => m.organizationId)),
];
const orgIds = [...new Set(userMemberships.map((m) => m.organizationId))];
const whereExpr = inArray(
sql`${sql.identifier(organizations.id.name)}`,
orgIds,
Expand Down
Loading