diff --git a/back/methods/account/privileges.js b/back/methods/account/privileges.js index d3aa9bf59..5c5e7409d 100644 --- a/back/methods/account/privileges.js +++ b/back/methods/account/privileges.js @@ -41,9 +41,6 @@ module.exports = Self => { const user = await models.Account.findById(userId, {fields: ['hasGrant']}, myOptions); - if (!user.hasGrant) - throw new UserError(`You don't have grant privilege`); - const userToUpdate = await models.Account.findById(id, { fields: ['id', 'name', 'hasGrant', 'roleFk', 'password'], include: { @@ -54,15 +51,22 @@ module.exports = Self => { } }, myOptions); + if (!user.hasGrant) + throw new UserError(`You don't have grant privilege`); + + const hasRoleFromUser = await models.Account.hasRole(userId, userToUpdate.role().name, myOptions); + + if (!hasRoleFromUser) + throw new UserError(`You don't own the role and you can't assign it to another user`); + if (hasGrant != null) userToUpdate.hasGrant = hasGrant; if (roleFk) { const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); const hasRole = await models.Account.hasRole(userId, role.name, myOptions); - const hasRoleFromUser = await models.Account.hasRole(userId, userToUpdate.role().name, myOptions); - if (!hasRole || !hasRoleFromUser) + if (!hasRole) throw new UserError(`You don't own the role and you can't assign it to another user`); userToUpdate.roleFk = roleFk; diff --git a/back/methods/account/specs/privileges.spec.js b/back/methods/account/specs/privileges.spec.js index 959130e8b..edfe0f03f 100644 --- a/back/methods/account/specs/privileges.spec.js +++ b/back/methods/account/specs/privileges.spec.js @@ -4,6 +4,8 @@ describe('account privileges()', () => { const employeeId = 1; const developerId = 9; const sysadminId = 66; + const itBossId = 104; + const rootId = 100; const clarkKent = 1103; it('should throw an error when user not has privileges', async() => { @@ -33,12 +35,26 @@ describe('account privileges()', () => { try { const options = {transaction: tx}; - const root = await models.Role.findOne({ - where: { - name: 'root' - } - }, options); - await models.Account.privileges(ctx, employeeId, root.id, null, options); + await models.Account.privileges(ctx, employeeId, rootId, null, options); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toContain(`You don't own the role and you can't assign it to another user`); + }); + + it('should throw an error when user has privileges but not has the role from user', async() => { + const ctx = {req: {accessToken: {userId: sysadminId}}}; + const tx = await models.Account.beginTransaction({}); + + let error; + try { + const options = {transaction: tx}; + + await models.Account.privileges(ctx, itBossId, developerId, null, options); await tx.rollback(); } catch (e) {