feat: write REST API endpoint to delete role

This commit is contained in:
Ali BARIN
2024-09-05 15:31:24 +00:00
parent ea667bb6a9
commit 0b6c28422c
4 changed files with 187 additions and 0 deletions

View File

@@ -1,6 +1,8 @@
import { ValidationError } from 'objection';
import Base from './base.js';
import Permission from './permission.js';
import User from './user.js';
import SamlAuthProvider from './saml-auth-provider.ee.js';
import NotAuthorizedError from '../errors/not-authorized.js';
class Role extends Base {
@@ -85,6 +87,59 @@ class Role extends Base {
});
});
}
async deleteWithPermissions() {
return await Role.transaction(async (trx) => {
await this.$relatedQuery('permissions', trx).delete();
return await this.$query(trx).delete();
});
}
async $beforeDelete(queryContext) {
await super.$beforeDelete(queryContext);
if (this.isAdmin) {
throw new NotAuthorizedError('The admin role cannot be deleted!');
}
const userCount = await this.$relatedQuery('users').limit(1).resultSize();
const hasUsers = userCount > 0;
if (hasUsers) {
throw new ValidationError({
data: {
role: [
{
message: `All users must be migrated away from the "${this.name}" role.`,
},
],
},
type: 'ValidationError',
});
}
const samlAuthProviderUsingDefaultRole = await SamlAuthProvider.query()
.where({
default_role_id: this.id,
})
.limit(1)
.first();
if (samlAuthProviderUsingDefaultRole) {
throw new ValidationError({
data: {
samlAuthProvider: [
{
message:
'You need to change the default role in the SAML configuration before deleting this role.',
},
],
},
type: 'ValidationError',
});
}
}
}
export default Role;