-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathrole.service.ts
436 lines (406 loc) · 15.9 KB
/
role.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import { Injectable } from '@nestjs/common';
import {
CreateRoleInput,
DeletionResponse,
DeletionResult,
Permission,
UpdateRoleInput,
} from '@vendure/common/lib/generated-types';
import {
CUSTOMER_ROLE_CODE,
CUSTOMER_ROLE_DESCRIPTION,
SUPER_ADMIN_ROLE_CODE,
SUPER_ADMIN_ROLE_DESCRIPTION,
} from '@vendure/common/lib/shared-constants';
import { ID, PaginatedList } from '@vendure/common/lib/shared-types';
import { unique } from '@vendure/common/lib/unique';
import { RequestContext } from '../../api/common/request-context';
import { RelationPaths } from '../../api/decorators/relations.decorator';
import { getAllPermissionsMetadata } from '../../common/constants';
import {
EntityNotFoundError,
ForbiddenError,
InternalServerError,
UserInputError,
} from '../../common/error/errors';
import { ListQueryOptions } from '../../common/types/common-types';
import { assertFound, idsAreEqual } from '../../common/utils';
import { ConfigService } from '../../config/config.service';
import { TransactionalConnection } from '../../connection/transactional-connection';
import { Channel } from '../../entity/channel/channel.entity';
import { Role } from '../../entity/role/role.entity';
import { User } from '../../entity/user/user.entity';
import { EventBus } from '../../event-bus';
import { RoleEvent } from '../../event-bus/events/role-event';
import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder';
import {
getChannelPermissions,
getUserChannelsPermissions,
} from '../helpers/utils/get-user-channels-permissions';
import { patchEntity } from '../helpers/utils/patch-entity';
import { ChannelService } from './channel.service';
/**
* @description
* Contains methods relating to {@link Role} entities.
*
* @docsCategory services
*/
@Injectable()
export class RoleService {
constructor(
private connection: TransactionalConnection,
private channelService: ChannelService,
private listQueryBuilder: ListQueryBuilder,
private configService: ConfigService,
private eventBus: EventBus,
) {}
async initRoles() {
await this.ensureSuperAdminRoleExists();
await this.ensureCustomerRoleExists();
await this.ensureRolesHaveValidPermissions();
}
findAll(
ctx: RequestContext,
options?: ListQueryOptions<Role>,
relations?: RelationPaths<Role>,
): Promise<PaginatedList<Role>> {
return this.listQueryBuilder
.build(Role, options, { relations: unique([...(relations ?? []), 'channels']), ctx })
.getManyAndCount()
.then(async ([items, totalItems]) => {
const visibleRoles: Role[] = [];
for (const item of items) {
const canRead = await this.activeUserCanReadRole(ctx, item);
if (canRead) {
visibleRoles.push(item);
}
}
return {
items: visibleRoles,
totalItems,
};
});
}
findOne(ctx: RequestContext, roleId: ID, relations?: RelationPaths<Role>): Promise<Role | undefined> {
return this.connection
.getRepository(ctx, Role)
.findOne({
where: { id: roleId },
relations: unique([...(relations ?? []), 'channels']),
})
.then(async result => {
if (result && (await this.activeUserCanReadRole(ctx, result))) {
return result;
}
});
}
getChannelsForRole(ctx: RequestContext, roleId: ID): Promise<Channel[]> {
return this.findOne(ctx, roleId).then(role => (role ? role.channels : []));
}
/**
* @description
* Returns the special SuperAdmin Role, which always exists in Vendure.
*/
getSuperAdminRole(ctx?: RequestContext): Promise<Role> {
return this.getRoleByCode(ctx, SUPER_ADMIN_ROLE_CODE).then(role => {
if (!role) {
throw new InternalServerError('error.super-admin-role-not-found');
}
return role;
});
}
/**
* @description
* Returns the special Customer Role, which always exists in Vendure.
*/
getCustomerRole(ctx?: RequestContext): Promise<Role> {
return this.getRoleByCode(ctx, CUSTOMER_ROLE_CODE).then(role => {
if (!role) {
throw new InternalServerError('error.customer-role-not-found');
}
return role;
});
}
/**
* @description
* Returns all the valid Permission values
*/
getAllPermissions(): string[] {
return Object.values(Permission);
}
/**
* @description
* Returns true if the User has the specified permission on that Channel
*/
async userHasPermissionOnChannel(
ctx: RequestContext,
channelId: ID,
permission: Permission,
): Promise<boolean> {
return this.userHasAnyPermissionsOnChannel(ctx, channelId, [permission]);
}
/**
* @description
* Returns true if the User has any of the specified permissions on that Channel
*/
async userHasAnyPermissionsOnChannel(
ctx: RequestContext,
channelId: ID,
permissions: Permission[],
): Promise<boolean> {
const permissionsOnChannel = await this.getActiveUserPermissionsOnChannel(ctx, channelId);
for (const permission of permissions) {
if (permissionsOnChannel.includes(permission)) {
return true;
}
}
return false;
}
private async activeUserCanReadRole(ctx: RequestContext, role: Role): Promise<boolean> {
const permissionsRequired = getChannelPermissions([role]);
for (const channelPermissions of permissionsRequired) {
const activeUserHasRequiredPermissions = await this.userHasAllPermissionsOnChannel(
ctx,
channelPermissions.id,
channelPermissions.permissions,
);
if (!activeUserHasRequiredPermissions) {
return false;
}
}
return true;
}
/**
* @description
* Returns true if the User has all the specified permissions on that Channel
*/
async userHasAllPermissionsOnChannel(
ctx: RequestContext,
channelId: ID,
permissions: Permission[],
): Promise<boolean> {
const permissionsOnChannel = await this.getActiveUserPermissionsOnChannel(ctx, channelId);
for (const permission of permissions) {
if (!permissionsOnChannel.includes(permission)) {
return false;
}
}
return true;
}
private async getActiveUserPermissionsOnChannel(
ctx: RequestContext,
channelId: ID,
): Promise<Permission[]> {
if (ctx.activeUserId == null) {
return [];
}
const user = await this.connection.getEntityOrThrow(ctx, User, ctx.activeUserId, {
relations: ['roles', 'roles.channels'],
});
const userChannels = getUserChannelsPermissions(user);
const channel = userChannels.find(c => idsAreEqual(c.id, channelId));
if (!channel) {
return [];
}
return channel.permissions;
}
async create(ctx: RequestContext, input: CreateRoleInput): Promise<Role> {
this.checkPermissionsAreValid(input.permissions);
let targetChannels: Channel[] = [];
if (input.channelIds) {
targetChannels = await this.getPermittedChannels(ctx, input.channelIds);
} else {
targetChannels = [ctx.channel];
}
await this.checkActiveUserHasSufficientPermissions(ctx, targetChannels, input.permissions);
const role = await this.createRoleForChannels(ctx, input, targetChannels);
await this.eventBus.publish(new RoleEvent(ctx, role, 'created', input));
return role;
}
async update(ctx: RequestContext, input: UpdateRoleInput): Promise<Role> {
this.checkPermissionsAreValid(input.permissions);
const role = await this.findOne(ctx, input.id);
if (!role) {
throw new EntityNotFoundError('Role', input.id);
}
if (role.code === SUPER_ADMIN_ROLE_CODE || role.code === CUSTOMER_ROLE_CODE) {
throw new InternalServerError('error.cannot-modify-role', { roleCode: role.code });
}
const targetChannels = input.channelIds
? await this.getPermittedChannels(ctx, input.channelIds)
: undefined;
if (input.permissions) {
await this.checkActiveUserHasSufficientPermissions(
ctx,
targetChannels ?? role.channels,
input.permissions,
);
}
const updatedRole = patchEntity(role, {
code: input.code,
description: input.description,
permissions: input.permissions
? unique([Permission.Authenticated, ...input.permissions])
: undefined,
});
if (targetChannels) {
updatedRole.channels = targetChannels;
}
await this.connection.getRepository(ctx, Role).save(updatedRole, { reload: false });
await this.eventBus.publish(new RoleEvent(ctx, role, 'updated', input));
return await assertFound(this.findOne(ctx, role.id));
}
async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> {
const role = await this.findOne(ctx, id);
if (!role) {
throw new EntityNotFoundError('Role', id);
}
if (role.code === SUPER_ADMIN_ROLE_CODE || role.code === CUSTOMER_ROLE_CODE) {
throw new InternalServerError('error.cannot-delete-role', { roleCode: role.code });
}
const deletedRole = new Role(role);
await this.connection.getRepository(ctx, Role).remove(role);
await this.eventBus.publish(new RoleEvent(ctx, deletedRole, 'deleted', id));
return {
result: DeletionResult.DELETED,
};
}
async assignRoleToChannel(ctx: RequestContext, roleId: ID, channelId: ID) {
await this.channelService.assignToChannels(ctx, Role, roleId, [channelId]);
}
private async getPermittedChannels(ctx: RequestContext, channelIds: ID[]): Promise<Channel[]> {
let permittedChannels: Channel[] = [];
for (const channelId of channelIds) {
const channel = await this.connection.getEntityOrThrow(ctx, Channel, channelId);
const hasPermission = await this.userHasPermissionOnChannel(
ctx,
channelId,
Permission.CreateAdministrator,
);
if (!hasPermission) {
throw new ForbiddenError();
}
permittedChannels = [...permittedChannels, channel];
}
return permittedChannels;
}
private checkPermissionsAreValid(permissions?: Permission[] | null) {
if (!permissions) {
return;
}
const allAssignablePermissions = this.getAllAssignablePermissions();
for (const permission of permissions) {
if (!allAssignablePermissions.includes(permission) || permission === Permission.SuperAdmin) {
throw new UserInputError('error.permission-invalid', { permission });
}
}
}
/**
* @description
* Checks that the active User has sufficient Permissions on the target Channels to create
* a Role with the given Permissions. The rule is that an Administrator may only grant
* Permissions that they themselves already possess.
*/
private async checkActiveUserHasSufficientPermissions(
ctx: RequestContext,
targetChannels: Channel[],
permissions: Permission[],
) {
const permissionsRequired = getChannelPermissions([
new Role({
permissions: unique([Permission.Authenticated, ...permissions]),
channels: targetChannels,
}),
]);
for (const channelPermissions of permissionsRequired) {
const activeUserHasRequiredPermissions = await this.userHasAllPermissionsOnChannel(
ctx,
channelPermissions.id,
channelPermissions.permissions,
);
if (!activeUserHasRequiredPermissions) {
throw new UserInputError('error.active-user-does-not-have-sufficient-permissions');
}
}
}
private getRoleByCode(ctx: RequestContext | undefined, code: string) {
const repository = ctx
? this.connection.getRepository(ctx, Role)
: this.connection.rawConnection.getRepository(Role);
return repository.findOne({
where: { code },
});
}
/**
* Ensure that the SuperAdmin role exists and that it has all possible Permissions.
*/
private async ensureSuperAdminRoleExists() {
const assignablePermissions = this.getAllAssignablePermissions();
try {
const superAdminRole = await this.getSuperAdminRole();
superAdminRole.permissions = assignablePermissions;
await this.connection.rawConnection.getRepository(Role).save(superAdminRole, { reload: false });
} catch (err: any) {
const defaultChannel = await this.channelService.getDefaultChannel();
await this.createRoleForChannels(
RequestContext.empty(),
{
code: SUPER_ADMIN_ROLE_CODE,
description: SUPER_ADMIN_ROLE_DESCRIPTION,
permissions: assignablePermissions,
},
[defaultChannel],
);
}
}
/**
* The Customer Role is a special case which must always exist.
*/
private async ensureCustomerRoleExists() {
try {
await this.getCustomerRole();
} catch (err: any) {
const defaultChannel = await this.channelService.getDefaultChannel();
await this.createRoleForChannels(
RequestContext.empty(),
{
code: CUSTOMER_ROLE_CODE,
description: CUSTOMER_ROLE_DESCRIPTION,
permissions: [Permission.Authenticated],
},
[defaultChannel],
);
}
}
/**
* Since custom permissions can be added and removed by config, there may exist one or more Roles with
* invalid permissions (i.e. permissions that were set previously to a custom permission, which has been
* subsequently removed from config). This method should run on startup to ensure that any such invalid
* permissions are removed from those Roles.
*/
private async ensureRolesHaveValidPermissions() {
const roles = await this.connection.rawConnection.getRepository(Role).find();
const assignablePermissions = this.getAllAssignablePermissions();
for (const role of roles) {
const invalidPermissions = role.permissions.filter(p => !assignablePermissions.includes(p));
if (invalidPermissions.length) {
role.permissions = role.permissions.filter(p => assignablePermissions.includes(p));
await this.connection.rawConnection.getRepository(Role).save(role);
}
}
}
private createRoleForChannels(ctx: RequestContext, input: CreateRoleInput, channels: Channel[]) {
const role = new Role({
code: input.code,
description: input.description,
permissions: unique([Permission.Authenticated, ...input.permissions]),
});
role.channels = channels;
return this.connection.getRepository(ctx, Role).save(role);
}
private getAllAssignablePermissions(): Permission[] {
return getAllPermissionsMetadata(this.configService.authOptions.customPermissions)
.filter(p => p.assignable)
.map(p => p.name as Permission);
}
}