/
roles.ts
332 lines (271 loc) · 9.06 KB
/
roles.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
import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import {
isRoleAddUserToRoleProps,
isRoleCreateProps,
isRoleDeleteProps,
isRoleRemoveUserFromRoleProps,
isRoleUpdateProps,
} from '@rocket.chat/rest-typings';
import type { IRole } from '@rocket.chat/core-typings';
import { Roles } from '@rocket.chat/models';
import { api } from '@rocket.chat/core-services';
import { Users } from '../../../models/server';
import { API } from '../api';
import { hasRole } from '../../../authorization/server';
import { getUsersInRolePaginated } from '../../../authorization/server/functions/getUsersInRole';
import { settings } from '../../../settings/server/index';
import { apiDeprecationLogger } from '../../../lib/server/lib/deprecationWarningLogger';
import { hasAnyRoleAsync } from '../../../authorization/server/functions/hasRole';
import { hasPermissionAsync } from '../../../authorization/server/functions/hasPermission';
import { updateRole } from '../../../../server/lib/roles/updateRole';
import { insertRole } from '../../../../server/lib/roles/insertRole';
API.v1.addRoute(
'roles.list',
{ authRequired: true },
{
async get() {
const roles = await Roles.find({}, { projection: { _updatedAt: 0 } }).toArray();
return API.v1.success({ roles });
},
},
);
API.v1.addRoute(
'roles.sync',
{ authRequired: true },
{
async get() {
check(
this.queryParams,
Match.ObjectIncluding({
updatedSince: Match.Where((value: unknown): value is string => typeof value === 'string' && !Number.isNaN(Date.parse(value))),
}),
);
const { updatedSince } = this.queryParams;
return API.v1.success({
roles: {
update: await Roles.findByUpdatedDate(new Date(updatedSince)).toArray(),
remove: await Roles.trashFindDeletedAfter(new Date(updatedSince)).toArray(),
},
});
},
},
);
API.v1.addRoute(
'roles.create',
{ authRequired: true },
{
async post() {
if (!isRoleCreateProps(this.bodyParams)) {
throw new Meteor.Error('error-invalid-role-properties', 'The role properties are invalid.');
}
const userId = Meteor.userId();
if (!userId || !(await hasPermissionAsync(userId, 'access-permissions'))) {
throw new Meteor.Error('error-action-not-allowed', 'Accessing permissions is not allowed');
}
const { name, scope, description, mandatory2fa } = this.bodyParams;
if (await Roles.findOneByIdOrName(name)) {
throw new Meteor.Error('error-duplicate-role-names-not-allowed', 'Role name already exists');
}
const roleData = {
description: description || '',
...(mandatory2fa !== undefined && { mandatory2fa }),
name,
scope: scope || 'Users',
protected: false,
};
const options = {
broadcastUpdate: settings.get<boolean>('UI_DisplayRoles'),
};
const role = insertRole(roleData, options);
return API.v1.success({
role,
});
},
},
);
API.v1.addRoute(
'roles.addUserToRole',
{ authRequired: true },
{
async post() {
if (!isRoleAddUserToRoleProps(this.bodyParams)) {
throw new Meteor.Error('error-invalid-role-properties', isRoleAddUserToRoleProps.errors?.map((error) => error.message).join('\n'));
}
const user = this.getUserFromParams();
const { roleId, roleName, roomId } = this.bodyParams;
if (!roleId) {
if (!roleName) {
return API.v1.failure('error-invalid-role-properties');
}
apiDeprecationLogger.warn(`Assigning roles by name is deprecated and will be removed on the next major release of Rocket.Chat`);
}
const role = roleId ? await Roles.findOneById(roleId) : await Roles.findOneByIdOrName(roleName as string);
if (!role) {
return API.v1.failure('error-role-not-found', 'Role not found');
}
if (hasRole(user._id, role._id, roomId)) {
throw new Meteor.Error('error-user-already-in-role', 'User already in role');
}
await Meteor.call('authorization:addUserToRole', role._id, user.username, roomId);
return API.v1.success({
role,
});
},
},
);
API.v1.addRoute(
'roles.getUsersInRole',
{ authRequired: true },
{
async get() {
const { roomId, role } = this.queryParams;
const { offset, count = 50 } = this.getPaginationItems();
const projection = {
name: 1,
username: 1,
emails: 1,
avatarETag: 1,
createdAt: 1,
_updatedAt: 1,
};
if (!role) {
throw new Meteor.Error('error-param-not-provided', 'Query param "role" is required');
}
if (!(await hasPermissionAsync(this.userId, 'access-permissions'))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed');
}
if (roomId && !(await hasPermissionAsync(this.userId, 'view-other-user-channels'))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed');
}
const options = { projection: { _id: 1 } };
let roleData = await Roles.findOneById<Pick<IRole, '_id'>>(role, options);
if (!roleData) {
roleData = await Roles.findOneByName<Pick<IRole, '_id'>>(role, options);
if (!roleData) {
throw new Meteor.Error('error-invalid-roleId');
}
apiDeprecationLogger.warn(`Querying roles by name is deprecated and will be removed on the next major release of Rocket.Chat`);
}
const { cursor, totalCount } = await getUsersInRolePaginated(roleData._id, roomId, {
limit: count as number,
sort: { username: 1 },
skip: offset as number,
projection,
});
const [users, total] = await Promise.all([cursor.toArray(), totalCount]);
return API.v1.success({ users, total });
},
},
);
API.v1.addRoute(
'roles.update',
{ authRequired: true },
{
async post() {
if (!isRoleUpdateProps(this.bodyParams)) {
throw new Meteor.Error('error-invalid-role-properties', 'The role properties are invalid.');
}
if (!(await hasPermissionAsync(this.userId, 'access-permissions'))) {
throw new Meteor.Error('error-action-not-allowed', 'Accessing permissions is not allowed');
}
const { roleId, name, scope, description, mandatory2fa } = this.bodyParams;
const roleData = {
description: description || '',
...(mandatory2fa !== undefined && { mandatory2fa }),
name,
scope: scope || 'Users',
protected: false,
};
const options = {
broadcastUpdate: settings.get<boolean>('UI_DisplayRoles'),
};
const role = updateRole(roleId, roleData, options);
return API.v1.success({
role,
});
},
},
);
API.v1.addRoute(
'roles.delete',
{ authRequired: true },
{
async post() {
const { bodyParams } = this;
if (!isRoleDeleteProps(bodyParams)) {
throw new Meteor.Error('error-invalid-role-properties', 'The role properties are invalid.');
}
if (!(await hasPermissionAsync(this.userId, 'access-permissions'))) {
throw new Meteor.Error('error-action-not-allowed', 'Accessing permissions is not allowed');
}
const role = await Roles.findOneByIdOrName(bodyParams.roleId);
if (!role) {
throw new Meteor.Error('error-invalid-roleId', 'This role does not exist');
}
if (role.protected) {
throw new Meteor.Error('error-role-protected', 'Cannot delete a protected role');
}
const existingUsers = await Roles.findUsersInRole(role._id);
if (existingUsers && (await existingUsers.count()) > 0) {
throw new Meteor.Error('error-role-in-use', "Cannot delete role because it's in use");
}
await Roles.removeById(role._id);
return API.v1.success();
},
},
);
API.v1.addRoute(
'roles.removeUserFromRole',
{ authRequired: true },
{
async post() {
const { bodyParams } = this;
if (!isRoleRemoveUserFromRoleProps(bodyParams)) {
throw new Meteor.Error('error-invalid-role-properties', 'The role properties are invalid.');
}
const { roleId, roleName, username, scope } = bodyParams;
if (!(await hasPermissionAsync(this.userId, 'access-permissions'))) {
throw new Meteor.Error('error-not-allowed', 'Accessing permissions is not allowed');
}
if (!roleId) {
if (!roleName) {
return API.v1.failure('error-invalid-role-properties');
}
apiDeprecationLogger.warn(`Unassigning roles by name is deprecated and will be removed on the next major release of Rocket.Chat`);
}
const user = Users.findOneByUsername(username);
if (!user) {
throw new Meteor.Error('error-invalid-user', 'There is no user with this username');
}
const role = roleId ? await Roles.findOneById(roleId) : await Roles.findOneByIdOrName(roleName as string);
if (!role) {
throw new Meteor.Error('error-invalid-roleId', 'This role does not exist');
}
if (!(await hasAnyRoleAsync(user._id, [role._id], scope))) {
throw new Meteor.Error('error-user-not-in-role', 'User is not in this role');
}
if (role._id === 'admin') {
const adminCount = await (await Roles.findUsersInRole('admin')).count();
if (adminCount === 1) {
throw new Meteor.Error('error-admin-required', 'You need to have at least one admin');
}
}
await Roles.removeUserRoles(user._id, [role._id], scope);
if (settings.get('UI_DisplayRoles')) {
api.broadcast('user.roleUpdate', {
type: 'removed',
_id: role._id,
u: {
_id: user._id,
username: user.username,
},
scope,
});
}
return API.v1.success({
role,
});
},
},
);