-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Expand file tree
/
Copy pathrestrictQuery.ts
More file actions
67 lines (57 loc) · 2.4 KB
/
restrictQuery.ts
File metadata and controls
67 lines (57 loc) · 2.4 KB
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
import type { ILivechatDepartment, IOmnichannelRoom } from '@rocket.chat/core-typings';
import { LivechatDepartment } from '@rocket.chat/models';
import type { FilterOperators } from 'mongodb';
import { cbLogger } from './logger';
import { getUnitsFromUser, memoizedGetDepartmentsFromUserRoles, memoizedGetUnitFromUserRoles } from '../methods/getUnitsFromUserRoles';
export const restrictQuery = async ({
originalQuery = {},
unitsFilter,
userId,
}: {
originalQuery?: FilterOperators<IOmnichannelRoom>;
unitsFilter?: string[];
userId?: string;
}) => {
const query = { ...originalQuery };
let userUnits = await getUnitsFromUser(userId);
if (!Array.isArray(userUnits)) {
if (Array.isArray(unitsFilter) && unitsFilter.length) {
return { ...query, departmentAncestors: { $in: unitsFilter } };
}
return query;
}
if (Array.isArray(unitsFilter) && unitsFilter.length) {
const userUnit = new Set([...userUnits]);
const filteredUnits = new Set(unitsFilter);
// IF user is trying to filter by a unit he doens't have access to, apply empty filter (no matches)
userUnits = [...userUnit.intersection(filteredUnits)];
}
// TODO: units is meant to include units and departments, however, here were only using them as units
// We have to change the filter to something like { $or: [{ ancestors: {$in: units }}, {_id: {$in: units}}] }
const departments = await LivechatDepartment.find({ ancestors: { $in: userUnits } }, { projection: { _id: 1 } }).toArray();
const expressions = query.$and || [];
const condition = {
$or: [{ departmentAncestors: { $in: userUnits } }, { departmentId: { $in: departments.map(({ _id }) => _id) } }],
};
query.$and = [condition, ...expressions];
cbLogger.debug({ msg: 'Applying room query restrictions', userUnits });
return query;
};
export const restrictDepartmentsQuery = async ({
originalQuery = {},
userId,
}: {
originalQuery?: FilterOperators<ILivechatDepartment>;
userId: string;
}) => {
const query: FilterOperators<ILivechatDepartment> = { ...originalQuery };
const userUnits = await memoizedGetUnitFromUserRoles(userId);
const userDepartments = await memoizedGetDepartmentsFromUserRoles(userId);
const expressions = query.$and || [];
const condition = {
$or: [{ ancestors: { $in: userUnits } }, { _id: { $in: userDepartments } }],
};
query.$and = [condition, ...expressions];
cbLogger.debug({ msg: 'Applying department query restrictions', userUnits });
return query;
};