Skip to content

Commit 8c98e1a

Browse files
committed
fix(core): fix create org role API
1 parent 7556c16 commit 8c98e1a

File tree

4 files changed

+133
-18
lines changed

4 files changed

+133
-18
lines changed

packages/core/src/routes/organization-role/index.openapi.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
"description": "The organization role was created successfully."
4747
},
4848
"422": {
49-
"description": "The organization role name is already in use."
49+
"description": "The organization role name is already in use, or at least one of the IDs (organizationScopeIds or resourceScopeIds) provided is invalid. For example, the organization scope ID or resource scope ID does not exist."
5050
}
5151
}
5252
}

packages/core/src/routes/organization-role/index.ts

+46-17
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@ import {
66
type OrganizationRoleKeys,
77
} from '@logto/schemas';
88
import { generateStandardId } from '@logto/shared';
9-
import { condArray } from '@silverhand/essentials';
9+
import { condArray, tryThat } from '@silverhand/essentials';
1010
import { z } from 'zod';
1111

12+
import RequestError from '#src/errors/RequestError/index.js';
1213
import { buildManagementApiContext } from '#src/libraries/hook/utils.js';
1314
import koaGuard from '#src/middleware/koa-guard.js';
1415
import koaPagination from '#src/middleware/koa-pagination.js';
@@ -93,6 +94,28 @@ export default function organizationRoleRoutes<T extends ManagementApiRouter>(
9394
resourceScopeIds: z.array(z.string()).default([]),
9495
});
9596

97+
/** Helper function to handle scope insertion with error handling */
98+
const insertScopesWithErrorHandling = async (
99+
roleId: string,
100+
insertFunction: () => Promise<unknown>,
101+
errorCode:
102+
| 'organization.roles.invalid_scope_ids'
103+
| 'organization.roles.invalid_resource_scope_ids'
104+
) => {
105+
await tryThat(
106+
async () => insertFunction(),
107+
(error) => {
108+
void roles.deleteById(roleId);
109+
110+
throw new RequestError({
111+
code: errorCode,
112+
status: 422,
113+
details: error instanceof Error ? error.message : String(error),
114+
});
115+
}
116+
);
117+
};
118+
96119
router.post(
97120
'/',
98121
koaGuard({
@@ -104,23 +127,29 @@ export default function organizationRoleRoutes<T extends ManagementApiRouter>(
104127
const { organizationScopeIds, resourceScopeIds, ...data } = ctx.guard.body;
105128
const role = await roles.insert({ id: generateStandardId(), ...data });
106129

107-
if (organizationScopeIds.length > 0) {
108-
await rolesScopes.insert(
109-
...organizationScopeIds.map((id) => ({
110-
organizationRoleId: role.id,
111-
organizationScopeId: id,
112-
}))
113-
);
114-
}
130+
await insertScopesWithErrorHandling(
131+
role.id,
132+
async () =>
133+
rolesScopes.insert(
134+
...organizationScopeIds.map((id) => ({
135+
organizationRoleId: role.id,
136+
organizationScopeId: id,
137+
}))
138+
),
139+
'organization.roles.invalid_scope_ids'
140+
);
115141

116-
if (resourceScopeIds.length > 0) {
117-
await rolesResourceScopes.insert(
118-
...resourceScopeIds.map((id) => ({
119-
organizationRoleId: role.id,
120-
scopeId: id,
121-
}))
122-
);
123-
}
142+
await insertScopesWithErrorHandling(
143+
role.id,
144+
async () =>
145+
rolesResourceScopes.insert(
146+
...resourceScopeIds.map((id) => ({
147+
organizationRoleId: role.id,
148+
scopeId: id,
149+
}))
150+
),
151+
'organization.roles.invalid_resource_scope_ids'
152+
);
124153

125154
ctx.body = role;
126155
ctx.status = 201;

packages/integration-tests/src/tests/api/organization/organization-role.test.ts

+82
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@ import { generateStandardId } from '@logto/shared';
44
import { isKeyInObject, pick } from '@silverhand/essentials';
55
import { HTTPError } from 'ky';
66

7+
import { createResource } from '#src/api/index.js';
8+
import { createScope } from '#src/api/scope.js';
79
import { OrganizationRoleApiTest, OrganizationScopeApiTest } from '#src/helpers/organization.js';
810
import { ScopeApiTest } from '#src/helpers/resource.js';
11+
import { generateScopeName } from '#src/utils.js';
912

1013
const randomId = () => generateStandardId(4);
1114

@@ -179,6 +182,85 @@ describe('organization role APIs', () => {
179182
const response = await roleApi.delete('0').catch((error: unknown) => error);
180183
expect(response instanceof HTTPError && response.response.status).toBe(404);
181184
});
185+
186+
it('should fail when creating a role with invalid organization scope IDs', async () => {
187+
const invalidScopeId = generateStandardId();
188+
const response = await roleApi
189+
.create({
190+
name: 'test' + randomId(),
191+
organizationScopeIds: [invalidScopeId],
192+
})
193+
.catch((error: unknown) => error);
194+
195+
assert(response instanceof HTTPError);
196+
const body: unknown = await response.response.json();
197+
expect(response.response.status).toBe(422);
198+
expect(body).toMatchObject(
199+
expect.objectContaining({
200+
code: 'organization.roles.invalid_scope_ids',
201+
})
202+
);
203+
204+
const roles = await roleApi.getList();
205+
expect(roles).toHaveLength(0);
206+
});
207+
208+
it('should fail when creating a role with invalid resource scope IDs', async () => {
209+
const invalidScopeId = generateStandardId();
210+
const response = await roleApi
211+
.create({
212+
name: 'test' + randomId(),
213+
resourceScopeIds: [invalidScopeId],
214+
})
215+
.catch((error: unknown) => error);
216+
217+
assert(response instanceof HTTPError);
218+
const body: unknown = await response.response.json();
219+
expect(response.response.status).toBe(422);
220+
expect(body).toMatchObject(
221+
expect.objectContaining({
222+
code: 'organization.roles.invalid_resource_scope_ids',
223+
})
224+
);
225+
226+
const roles = await roleApi.getList();
227+
expect(roles).toHaveLength(0);
228+
});
229+
230+
it('should successfully create a role with scope IDs are provided', async () => {
231+
const resource = await createResource();
232+
const scopeName = generateScopeName();
233+
const createdScope = await createScope(resource.id, scopeName);
234+
235+
const [scope1, scope2] = await Promise.all([
236+
scopeApi.create({ name: 'test' + randomId() }),
237+
scopeApi.create({ name: 'test' + randomId() }),
238+
]);
239+
const createdRole = await roleApi.create({
240+
name: 'test' + randomId(),
241+
organizationScopeIds: [scope1.id, scope2.id],
242+
resourceScopeIds: [createdScope.id],
243+
});
244+
245+
expect(createdRole).toHaveProperty('id');
246+
expect(createdRole).toHaveProperty('name');
247+
248+
const scopes = await roleApi.getScopes(createdRole.id);
249+
expect(scopes).toContainEqual(
250+
expect.objectContaining({
251+
name: scope1.name,
252+
})
253+
);
254+
expect(scopes).toContainEqual(
255+
expect.objectContaining({
256+
name: scope2.name,
257+
})
258+
);
259+
260+
const { resourceScopes } = await roleApi.get(createdRole.id);
261+
expect(resourceScopes.length).toBe(1);
262+
expect(resourceScopes[0]).toHaveProperty('name', scopeName);
263+
});
182264
});
183265

184266
describe('organization role - scope relations', () => {
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
const organizations = {
22
require_membership: 'The user must be a member of the organization to proceed.',
3+
roles: {
4+
invalid_scope_ids: 'The organization scope IDs are not valid.',
5+
invalid_resource_scope_ids: 'The resource scope IDs are not valid.',
6+
},
37
};
48

59
export default Object.freeze(organizations);

0 commit comments

Comments
 (0)