diff --git a/backend/src/schema/resolvers/users.js b/backend/src/schema/resolvers/users.js index 789ca2a37..55094f088 100644 --- a/backend/src/schema/resolvers/users.js +++ b/backend/src/schema/resolvers/users.js @@ -247,6 +247,7 @@ export default { switchUserRole: async (object, args, context, resolveInfo) => { const { role, id } = args + if (context.user.id === id) throw new Error('you-cannot-change-your-own-role') const session = context.driver.session() const writeTxResultPromise = session.writeTransaction(async (transaction) => { const switchUserRoleResponse = await transaction.run( diff --git a/backend/src/schema/resolvers/users.spec.js b/backend/src/schema/resolvers/users.spec.js index cce45ae6e..df0958342 100644 --- a/backend/src/schema/resolvers/users.spec.js +++ b/backend/src/schema/resolvers/users.spec.js @@ -45,6 +45,18 @@ const deleteUserMutation = gql` } ` +const switchUserRoleMutation = gql` + mutation($role: UserGroup!, $id: ID!) { + switchUserRole(role: $role, id: $id) { + name + role + id + updatedAt + email + } + } +` + beforeAll(() => { const { server } = createServer({ context: () => { @@ -458,3 +470,71 @@ describe('Delete a User as admin', () => { }) }) }) + +describe('switch user role', () => { + beforeEach(async () => { + user = await Factory.build('user', { + id: 'user', + role: 'user', + }) + admin = await Factory.build('user', { + role: 'admin', + id: 'admin', + }) + }) + + describe('as simple user', () => { + it('cannot change the role', async () => { + authenticatedUser = await user.toJson() + variables = { + id: 'user', + role: 'admin', + } + await expect(mutate({ mutation: switchUserRoleMutation, variables })).resolves.toEqual( + expect.objectContaining({ + errors: [ + expect.objectContaining({ + message: 'Not Authorised!', + }), + ], + }), + ) + }) + }) + + describe('as admin', () => { + it('changes the role of other user', async () => { + authenticatedUser = await admin.toJson() + variables = { + id: 'user', + role: 'moderator', + } + await expect(mutate({ mutation: switchUserRoleMutation, variables })).resolves.toEqual( + expect.objectContaining({ + data: { + switchUserRole: expect.objectContaining({ + role: 'moderator', + }), + }, + }), + ) + }) + + it('cannot change own role', async () => { + authenticatedUser = await admin.toJson() + variables = { + id: 'admin', + role: 'moderator', + } + await expect(mutate({ mutation: switchUserRoleMutation, variables })).resolves.toEqual( + expect.objectContaining({ + errors: [ + expect.objectContaining({ + message: 'you-cannot-change-your-own-role', + }), + ], + }), + ) + }) + }) +})