Files
outline/server/commands/userDestroyer.ts
2024-03-28 16:00:35 -07:00

68 lines
1.2 KiB
TypeScript

import { Op, Transaction } from "sequelize";
import { UserRole } from "@shared/types";
import { Event, User } from "@server/models";
import { ValidationError } from "../errors";
export default async function userDestroyer({
user,
actor,
ip,
transaction,
}: {
user: User;
actor: User;
ip: string;
transaction?: Transaction;
}) {
const { teamId } = user;
const usersCount = await User.count({
where: {
teamId,
},
});
if (usersCount === 1) {
throw ValidationError(
"Cannot delete last user on the team, delete the workspace instead."
);
}
if (user.isAdmin) {
const otherAdminsCount = await User.count({
where: {
role: UserRole.Admin,
teamId,
id: {
[Op.ne]: user.id,
},
},
});
if (otherAdminsCount === 0) {
throw ValidationError(
"Cannot delete account as only admin. Please make another user admin and try again."
);
}
}
await Event.create(
{
name: "users.delete",
actorId: actor.id,
userId: user.id,
teamId,
data: {
name: user.name,
},
ip,
},
{
transaction,
}
);
return user.destroy({
transaction,
});
}