prevent removing the last superadmin

Signed-off-by: Pierre Noël <petersg83@gmail.com>
This commit is contained in:
Pierre Noël 2020-06-16 16:29:10 +02:00 committed by Alexandre Bodin
parent 93fc900e10
commit 98f8275190
4 changed files with 23 additions and 7 deletions

View File

@ -93,7 +93,7 @@ module.exports = {
async delete(ctx) {
const { id } = ctx.params;
const deletedUser = await strapi.admin.services.user.deleteOne({ id });
const deletedUser = await strapi.admin.services.user.delete({ id });
if (!deletedUser) {
return ctx.notFound('User not found');

View File

@ -47,7 +47,6 @@ const assign = async (roleId, permissions = []) => {
try {
await validatePermissionsExist(permissions);
} catch (err) {
console.log('err', err);
throw strapi.errors.badRequest('ValidationError', err);
}

View File

@ -82,9 +82,6 @@ const update = async (params, attributes) => {
const rolesToBeUpdatedIds = rolesToBeUpdated.map(r => r.id).map(String);
const adminRole = await getAdmin();
console.log('rolesToBeUpdatedIds', rolesToBeUpdatedIds);
console.log(adminRole, adminRole.id);
if (rolesToBeUpdatedIds.includes(String(adminRole.id))) {
throw strapi.errors.badRequest(
'ValidationError',

View File

@ -47,6 +47,26 @@ const create = async attributes => {
* @returns {Promise<user>}
*/
const update = async (params, attributes) => {
// Check at least one super admin remains
if (_.has(attributes, 'roles')) {
const superAdminRole = await strapi.admin.services.role.getAdmin();
if (superAdminRole && !attributes.roles.map(String).includes(String(superAdminRole.id))) {
const usersWithAdminRole = await strapi
.query('user', 'admin')
.find({ roles: [superAdminRole.id] });
const usersWithAdminRoleIds = usersWithAdminRole.map(u => u.id).map(String);
const usersToBeModified = await strapi.query('user', 'admin').find(params);
const usersToBeModifiedIds = usersToBeModified.map(u => u.id).map(String);
if (_.difference(usersWithAdminRoleIds, usersToBeModifiedIds).length < 1) {
throw strapi.errors.badRequest(
'ValidationError',
'You must have at least one user with super admin role.'
);
}
}
}
// hash password if a new one is sent
if (_.has(attributes, 'password')) {
const hashedPassword = await strapi.admin.services.auth.hashPassword(attributes.password);
@ -136,7 +156,7 @@ const searchPage = async query => {
* @param query
* @returns {Promise<user>}
*/
const deleteOne = async query => {
const deleteFn = async query => {
return strapi.query('user', 'admin').delete(query);
};
@ -179,6 +199,6 @@ module.exports = {
findOne,
findPage,
searchPage,
deleteOne,
delete: deleteFn,
countUsersWithoutRole,
};