sync user clients to org on add/remove user org

This commit is contained in:
miloschwartz
2025-11-08 17:51:51 -08:00
parent a70799c8c0
commit 5602d8ee64
6 changed files with 332 additions and 37 deletions

View File

@@ -33,6 +33,7 @@ import { UserType } from "@server/types/UserTypes";
import { FeatureId } from "@server/lib/billing";
import { usageService } from "@server/lib/billing/usageService";
import { build } from "@server/build";
import { calculateUserClientsForOrgs } from "@server/lib/calculateUserClientsForOrgs";
const ensureTrailingSlash = (url: string): string => {
return url;
@@ -364,10 +365,18 @@ export async function validateOidcCallback(
);
if (!existingUserOrgs.length) {
// delete the user
// await db
// .delete(users)
// .where(eq(users.userId, existingUser.userId));
// delete all auto -provisioned user orgs
await db
.delete(userOrgs)
.where(
and(
eq(userOrgs.userId, existingUser.userId),
eq(userOrgs.autoProvisioned, true)
)
);
await calculateUserClientsForOrgs(existingUser.userId);
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
@@ -513,6 +522,8 @@ export async function validateOidcCallback(
userCount: userCount.length
});
}
await calculateUserClientsForOrgs(userId!, trx);
});
for (const orgCount of orgUserCounts) {
@@ -553,6 +564,24 @@ export async function validateOidcCallback(
);
}
// check for existing user orgs
const existingUserOrgs = await db
.select()
.from(userOrgs)
.where(and(eq(userOrgs.userId, existingUser.userId)));
if (!existingUserOrgs.length) {
logger.debug(
"No existing user orgs found for non-auto-provisioned IdP"
);
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
`User with username ${userIdentifier} is unprovisioned. This user must be added to an organization before logging in.`
)
);
}
const token = generateSessionToken();
const sess = await createSession(token, existingUser.userId);
const isSecure = req.protocol === "https";