diff --git a/apps/api/src/app/api/electric/[...path]/route.ts b/apps/api/src/app/api/electric/[...path]/route.ts index 847e3ca019a..8d7afabab83 100644 --- a/apps/api/src/app/api/electric/[...path]/route.ts +++ b/apps/api/src/app/api/electric/[...path]/route.ts @@ -31,7 +31,11 @@ export async function GET(request: Request): Promise { 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 }); } diff --git a/apps/api/src/app/api/electric/[...path]/utils.ts b/apps/api/src/app/api/electric/[...path]/utils.ts index 51ff261da78..1fe43868393 100644 --- a/apps/api/src/app/api/electric/[...path]/utils.ts +++ b/apps/api/src/app/api/electric/[...path]/utils.ts @@ -40,6 +40,7 @@ function build(table: PgTable, column: PgColumn, id: string): WhereClause { export async function buildWhereClause( tableName: string, organizationId: string, + userId: string, ): Promise { switch (tableName) { case "tasks": @@ -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,