Skip to content

Commit

Permalink
refactor: Improve user deletion
Browse files Browse the repository at this point in the history
The user deletion now uses a transaction to delete related data from multiple tables, including email, phone, authentication, oAuthClientSecrets, policyConsent, oAuthClientAuthorization, and oAuthToken. It also disconnects the user from any owned oAuthClients and groups.
  • Loading branch information
Baw-Appie committed Sep 16, 2024
1 parent 40df710 commit abeb2bc
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions src/routes/v1/admin/users/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,10 +264,38 @@ const userAdminHandler = (app: FastifyInstance, opts: FastifyPluginOptions, done
// actually delete if admin requested permanent deletion
// note: this could lead possible uuid collision for other apps.
if (permanent) {
await getPrismaClient().user.delete({
where: {
id: uuid,
},
const userId = uuid;
await getPrismaClient().$transaction(async (tx) => {
await tx.email.deleteMany({ where: { userId } });
await tx.phone.deleteMany({ where: { userId } });
await tx.authentication.deleteMany({ where: { userId } });
await tx.oAuthClientSecrets.deleteMany({ where: { userId } });
await tx.policyConsent.deleteMany({ where: { userId } });

const authorizations = await tx.oAuthClientAuthorization.findMany({ where: { userId } });
for (const auth of authorizations) {
await tx.oAuthToken.deleteMany({ where: { authorizationId: auth.id } });
}
await tx.oAuthClientAuthorization.deleteMany({ where: { userId } });

await tx.user.update({
where: { id: userId },
data: { groups: { set: [] } },
});

const ownedClients = await tx.oAuthClient.findMany({ where: { owners: { some: { id: userId } } } });
for (const client of ownedClients) {
await tx.oAuthClient.update({
where: { id: client.id },
data: {
owners: {
disconnect: { id: userId },
},
},
});
}

await tx.user.delete({ where: { id: userId } });
});
}

Expand Down

0 comments on commit abeb2bc

Please sign in to comment.