-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Expand file tree
/
Copy pathpermissions.service.ts
More file actions
306 lines (264 loc) · 9.51 KB
/
permissions.service.ts
File metadata and controls
306 lines (264 loc) · 9.51 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
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
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { msg } from '@lingui/core/macro';
import { PermissionFlagType } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { In, Repository } from 'typeorm';
import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
import { TOOL_PERMISSION_FLAGS } from 'src/engine/metadata-modules/permissions/constants/tool-permission-flags';
import {
PermissionsException,
PermissionsExceptionCode,
PermissionsExceptionMessage,
} from 'src/engine/metadata-modules/permissions/permissions.exception';
import { type UserWorkspacePermissions } from 'src/engine/metadata-modules/permissions/types/user-workspace-permissions';
import { RoleEntity } from 'src/engine/metadata-modules/role/role.entity';
import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';
import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@Injectable()
export class PermissionsService {
constructor(
private readonly userRoleService: UserRoleService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly apiKeyRoleService: ApiKeyRoleService,
@InjectRepository(RoleEntity)
private readonly roleRepository: Repository<RoleEntity>,
) {}
private isToolPermission(feature: string) {
return TOOL_PERMISSION_FLAGS.includes(feature);
}
public async getUserWorkspacePermissions({
userWorkspaceId,
workspaceId,
}: {
userWorkspaceId: string;
workspaceId: string;
}): Promise<UserWorkspacePermissions> {
const [roleOfUserWorkspace] = await this.userRoleService
.getRolesByUserWorkspaces({
userWorkspaceIds: [userWorkspaceId],
workspaceId,
})
.then((roles) => roles?.get(userWorkspaceId) ?? []);
if (!isDefined(roleOfUserWorkspace)) {
throw new PermissionsException(
PermissionsExceptionMessage.NO_ROLE_FOUND_FOR_USER_WORKSPACE,
PermissionsExceptionCode.NO_ROLE_FOUND_FOR_USER_WORKSPACE,
{
userFriendlyMessage: msg`Your role in this workspace could not be found. Please contact your workspace administrator.`,
},
);
}
const defaultSettingsPermissions =
this.getDefaultUserWorkspacePermissions().permissionFlags;
const permissionFlags = Object.keys(PermissionFlagType).reduce(
(acc, feature) => {
const hasBasePermission = this.isToolPermission(feature)
? roleOfUserWorkspace.canAccessAllTools
: roleOfUserWorkspace.canUpdateAllSettings;
return {
...acc,
[feature]:
hasBasePermission ||
roleOfUserWorkspace.permissionFlags.some(
(permissionFlag) => permissionFlag.flag === feature,
),
};
},
defaultSettingsPermissions,
);
const { rolesPermissions } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
'rolesPermissions',
]);
const objectsPermissions = rolesPermissions[roleOfUserWorkspace.id] ?? {};
return {
permissionFlags,
objectsPermissions,
};
}
public getDefaultUserWorkspacePermissions = () =>
({
permissionFlags: {
[PermissionFlagType.API_KEYS_AND_WEBHOOKS]: false,
[PermissionFlagType.WORKSPACE]: false,
[PermissionFlagType.WORKSPACE_MEMBERS]: false,
[PermissionFlagType.ROLES]: false,
[PermissionFlagType.DATA_MODEL]: false,
[PermissionFlagType.SECURITY]: false,
[PermissionFlagType.WORKFLOWS]: false,
[PermissionFlagType.APPLICATIONS]: false,
[PermissionFlagType.LAYOUTS]: false,
[PermissionFlagType.VIEWS]: false,
[PermissionFlagType.BILLING]: false,
[PermissionFlagType.AI_SETTINGS]: false,
[PermissionFlagType.AI]: false,
[PermissionFlagType.UPLOAD_FILE]: false,
[PermissionFlagType.DOWNLOAD_FILE]: false,
[PermissionFlagType.SEND_EMAIL_TOOL]: false,
[PermissionFlagType.HTTP_REQUEST_TOOL]: false,
[PermissionFlagType.IMPORT_CSV]: false,
[PermissionFlagType.EXPORT_CSV]: false,
[PermissionFlagType.CONNECTED_ACCOUNTS]: false,
[PermissionFlagType.IMPERSONATE]: false,
[PermissionFlagType.SSO_BYPASS]: false,
[PermissionFlagType.PROFILE_INFORMATION]: false,
},
objectsPermissions: {},
}) as const satisfies UserWorkspacePermissions;
public async userHasWorkspaceSettingPermission({
userWorkspaceId,
workspaceId,
setting,
apiKeyId,
}: {
userWorkspaceId?: string;
workspaceId: string;
setting: PermissionFlagType;
apiKeyId?: string;
}): Promise<boolean> {
if (isDefined(apiKeyId)) {
const roleId = await this.apiKeyRoleService.getRoleIdForApiKeyId(
apiKeyId,
workspaceId,
);
const role = await this.roleRepository.findOne({
where: { id: roleId, workspaceId },
relations: ['permissionFlags'],
});
if (!isDefined(role)) {
throw new PermissionsException(
PermissionsExceptionMessage.API_KEY_ROLE_NOT_FOUND,
PermissionsExceptionCode.API_KEY_ROLE_NOT_FOUND,
{
userFriendlyMessage: msg`The API key does not have a valid role assigned. Please check your API key configuration.`,
},
);
}
return this.checkRolePermissions(role, setting);
}
if (userWorkspaceId) {
const [roleOfUserWorkspace] = await this.userRoleService
.getRolesByUserWorkspaces({
userWorkspaceIds: [userWorkspaceId],
workspaceId,
})
.then((roles) => roles?.get(userWorkspaceId) ?? []);
if (!isDefined(roleOfUserWorkspace)) {
throw new PermissionsException(
PermissionsExceptionMessage.NO_ROLE_FOUND_FOR_USER_WORKSPACE,
PermissionsExceptionCode.NO_ROLE_FOUND_FOR_USER_WORKSPACE,
{
userFriendlyMessage: msg`Your role in this workspace could not be found. Please contact your workspace administrator.`,
},
);
}
return this.checkRolePermissions(roleOfUserWorkspace, setting);
}
throw new PermissionsException(
PermissionsExceptionMessage.NO_AUTHENTICATION_CONTEXT,
PermissionsExceptionCode.NO_AUTHENTICATION_CONTEXT,
{
userFriendlyMessage: msg`Authentication is required to access this feature. Please sign in and try again.`,
},
);
}
public checkRolePermissions(
role: RoleEntity,
setting: PermissionFlagType,
): boolean {
const hasBasePermission = this.isToolPermission(setting)
? role.canAccessAllTools
: role.canUpdateAllSettings;
if (hasBasePermission === true) {
return true;
}
const permissionFlags = role.permissionFlags ?? [];
return permissionFlags.some(
(permissionFlag) => permissionFlag.flag === setting,
);
}
private async getRolesFromPermissionConfig(
rolePermissionConfig: RolePermissionConfig,
workspaceId: string,
relations: string[] = [],
): Promise<{ roles: RoleEntity[]; useIntersection: boolean } | null> {
if ('shouldBypassPermissionChecks' in rolePermissionConfig) {
return null;
}
let roleIds: string[] = [];
let useIntersection = false;
if ('intersectionOf' in rolePermissionConfig) {
roleIds = rolePermissionConfig.intersectionOf;
useIntersection = true;
} else if ('unionOf' in rolePermissionConfig) {
roleIds = rolePermissionConfig.unionOf;
useIntersection = false;
}
if (roleIds.length === 0) {
throw new Error('No role IDs provided');
}
const roles = await this.roleRepository.find({
where: { id: In(roleIds), workspaceId },
relations,
});
if (roles.length !== roleIds.length) {
throw new Error('Some roles not found');
}
return { roles, useIntersection };
}
public async checkRolesPermissions(
rolePermissionConfig: RolePermissionConfig,
workspaceId: string,
setting: PermissionFlagType,
): Promise<boolean> {
try {
const result = await this.getRolesFromPermissionConfig(
rolePermissionConfig,
workspaceId,
['permissionFlags'],
);
if (result === null) {
return true;
}
const { roles, useIntersection } = result;
return useIntersection
? roles.every((role) => this.checkRolePermissions(role, setting))
: roles.some((role) => this.checkRolePermissions(role, setting));
} catch {
return false;
}
}
public async hasToolPermission(
rolePermissionConfig: RolePermissionConfig,
workspaceId: string,
flag: PermissionFlagType,
): Promise<boolean> {
try {
const result = await this.getRolesFromPermissionConfig(
rolePermissionConfig,
workspaceId,
['permissionFlags'],
);
if (result === null) {
return true;
}
const { roles, useIntersection } = result;
const checkRoleHasPermission = (role: RoleEntity) => {
if (role.canAccessAllTools === true) {
return true;
}
const permissionFlags = role.permissionFlags ?? [];
return permissionFlags.some(
(permissionFlag) => permissionFlag.flag === flag,
);
};
return useIntersection
? roles.every(checkRoleHasPermission)
: roles.some(checkRoleHasPermission);
} catch {
return false;
}
}
}