From 3e28af670caeed43fe3221f93ddcf0ec48a26a7c Mon Sep 17 00:00:00 2001 From: Ali BARIN Date: Fri, 8 Nov 2024 14:27:49 +0000 Subject: [PATCH] test(user): write tests for authorizedSteps --- packages/backend/src/models/user.test.js | 66 ++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/packages/backend/src/models/user.test.js b/packages/backend/src/models/user.test.js index 0c2aa655..50a5d2a7 100644 --- a/packages/backend/src/models/user.test.js +++ b/packages/backend/src/models/user.test.js @@ -16,6 +16,7 @@ import { createUser } from '../../test/factories/user.js'; import { createRole } from '../../test/factories/role.js'; import { createPermission } from '../../test/factories/permission.js'; import { createFlow } from '../../test/factories/flow.js'; +import { createStep } from '../../test/factories/step.js'; describe('User model', () => { it('tableName should return correct name', () => { @@ -307,4 +308,69 @@ describe('User model', () => { ); }); }); + + describe('authorizedSteps', () => { + it('should return user steps with isCreator condition', async () => { + const userRole = await createRole({ name: 'User' }); + + await createPermission({ + roleId: userRole.id, + subject: 'Flow', + action: 'read', + conditions: ['isCreator'], + }); + + const user = await createUser({ roleId: userRole.id }); + + const userWithRoleAndPermissions = await user + .$query() + .withGraphFetched({ role: true, permissions: true }); + + const userFlow = await createFlow({ userId: user.id }); + const userFlowStep = await createStep({ flowId: userFlow.id }); + const anotherUserFlow = await createFlow(); + await createStep({ flowId: anotherUserFlow.id }); + + expect(await userWithRoleAndPermissions.authorizedSteps).toStrictEqual([ + userFlowStep, + ]); + }); + + it('should return all steps without isCreator condition', async () => { + const userRole = await createRole({ name: 'User' }); + + await createPermission({ + roleId: userRole.id, + subject: 'Flow', + action: 'read', + conditions: [], + }); + + const user = await createUser({ roleId: userRole.id }); + + const userWithRoleAndPermissions = await user + .$query() + .withGraphFetched({ role: true, permissions: true }); + + const userFlow = await createFlow({ userId: user.id }); + const userFlowStep = await createStep({ flowId: userFlow.id }); + const anotherUserFlow = await createFlow(); + const anotherUserFlowStep = await createStep({ + flowId: anotherUserFlow.id, + }); + + expect(await userWithRoleAndPermissions.authorizedSteps).toStrictEqual([ + userFlowStep, + anotherUserFlowStep, + ]); + }); + + it('should throw an authorization error without Flow read permission', async () => { + const user = new User(); + + expect(() => user.authorizedSteps).toThrowError( + 'The user is not authorized!' + ); + }); + }); });