From fce887436d5a195cdb5ea9008a782efa0bb942ab Mon Sep 17 00:00:00 2001 From: miloschwartz Date: Thu, 6 Nov 2025 15:46:54 -0800 Subject: [PATCH] fix bug causing auto provision to override manually created users --- server/routers/idp/validateOidcCallback.ts | 42 +++++++++++++++------- 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/server/routers/idp/validateOidcCallback.ts b/server/routers/idp/validateOidcCallback.ts index 98bdfe44..376dd7bc 100644 --- a/server/routers/idp/validateOidcCallback.ts +++ b/server/routers/idp/validateOidcCallback.ts @@ -352,20 +352,38 @@ export async function validateOidcCallback( if (!userOrgInfo.length) { if (existingUser) { - // delete the user - // cascade will also delete org users + // get existing user orgs + const existingUserOrgs = await db + .select() + .from(userOrgs) + .where( + and( + eq(userOrgs.userId, existingUser.userId), + eq(userOrgs.autoProvisioned, false) + ) + ); - await db - .delete(users) - .where(eq(users.userId, existingUser.userId)); + if (!existingUserOrgs.length) { + // delete the user + await db + .delete(users) + .where(eq(users.userId, existingUser.userId)); + return next( + createHttpError( + HttpCode.UNAUTHORIZED, + `No policies matched for ${userIdentifier}. This user must be added to an organization before logging in.` + ) + ); + } + } else { + // no orgs to provision and user doesn't exist + return next( + createHttpError( + HttpCode.UNAUTHORIZED, + `No policies matched for ${userIdentifier}. This user must be added to an organization before logging in.` + ) + ); } - - return next( - createHttpError( - HttpCode.UNAUTHORIZED, - `No policies matched for ${userIdentifier}. This user must be added to an organization before logging in.` - ) - ); } const orgUserCounts: { orgId: string; userCount: number }[] = [];