fix: user(owner) delete bug (#4388)

Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
This commit is contained in:
Piyush Gupta
2024-12-04 13:35:48 +05:30
committed by GitHub
parent 9a66e26b00
commit f3c628ba76
2 changed files with 43 additions and 5 deletions

View File

@@ -3,6 +3,7 @@
import {
deleteMembership,
getMembershipsByUserId,
getOrganizationOwnerCount,
} from "@/app/(app)/environments/[environmentId]/settings/(organization)/general/lib/membership";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client-middleware";
@@ -94,16 +95,23 @@ export const deleteMembershipAction = authenticatedActionClient
throw new AuthenticationError("You cannot delete yourself from the organization");
}
const membership = await getMembershipByUserIdOrganizationId(ctx.user.id, parsedInput.organizationId);
const membership = await getMembershipByUserIdOrganizationId(
parsedInput.userId,
parsedInput.organizationId
);
if (!membership) {
throw new AuthenticationError("Not a member of this organization");
}
const memberships = await getMembershipsByUserId(ctx.user.id);
const isLastOwner = memberships?.filter((m) => m.role === "owner").length === 1;
if (membership.role === "owner" && isLastOwner) {
throw new ValidationError("You cannot delete the last owner of the organization");
const isOwner = membership.role === "owner";
if (isOwner) {
const ownerCount = await getOrganizationOwnerCount(parsedInput.organizationId);
if (ownerCount <= 1) {
throw new ValidationError("You cannot delete the last owner of the organization");
}
}
return await deleteMembership(parsedInput.userId, parsedInput.organizationId);

View File

@@ -12,6 +12,36 @@ import { ZOptionalNumber, ZString } from "@formbricks/types/common";
import { DatabaseError, UnknownError } from "@formbricks/types/errors";
import { TMember, TMembership } from "@formbricks/types/memberships";
export const getOrganizationOwnerCount = reactCache(
async (organizationId: string): Promise<number> =>
cache(
async () => {
validateInputs([organizationId, ZString]);
try {
const ownersCount = await prisma.membership.count({
where: {
organizationId,
role: "owner",
},
});
return ownersCount;
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
throw new DatabaseError(error.message);
}
throw error;
}
},
[`getOrganizationOwnerCount-${organizationId}`],
{
tags: [membershipCache.tag.byOrganizationId(organizationId)],
}
)()
);
export const getMembersByOrganizationId = reactCache(
async (organizationId: string, page?: number): Promise<TMember[]> =>
cache(