-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
roles.ts
196 lines (158 loc) · 5.69 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
import type { Query } from '@directus/types';
import { ForbiddenError, UnprocessableContentError } from '@directus/errors';
import type { AbstractServiceOptions, Alterations, Item, MutationOptions, PrimaryKey } from '../types/index.js';
import { ItemsService } from './items.js';
import { PermissionsService } from './permissions.js';
import { PresetsService } from './presets.js';
import { UsersService } from './users.js';
export class RolesService extends ItemsService {
constructor(options: AbstractServiceOptions) {
super('directus_roles', options);
}
private async checkForOtherAdminRoles(excludeKeys: PrimaryKey[]): Promise<void> {
// Make sure there's at least one admin role left after this deletion is done
const otherAdminRoles = await this.knex
.count('*', { as: 'count' })
.from('directus_roles')
.whereNotIn('id', excludeKeys)
.andWhere({ admin_access: true })
.first();
const otherAdminRolesCount = +(otherAdminRoles?.count || 0);
if (otherAdminRolesCount === 0) {
throw new UnprocessableContentError({ reason: `You can't delete the last admin role` });
}
}
private async checkForOtherAdminUsers(key: PrimaryKey, users: Alterations | Item[]): Promise<void> {
const role = await this.knex.select('admin_access').from('directus_roles').where('id', '=', key).first();
if (!role) throw new ForbiddenError();
// The users that will now be in this new non-admin role
let userKeys: PrimaryKey[] = [];
if (Array.isArray(users)) {
userKeys = users.map((user) => (typeof user === 'string' ? user : user['id'])).filter((id) => id);
} else {
userKeys = users.update.map((user) => user['id']).filter((id) => id);
}
const usersThatWereInRoleBefore = (await this.knex.select('id').from('directus_users').where('role', '=', key)).map(
(user) => user.id
);
const usersThatAreRemoved = usersThatWereInRoleBefore.filter((id) =>
Array.isArray(users) ? userKeys.includes(id) === false : users.delete.includes(id) === true
);
const usersThatAreAdded = Array.isArray(users) ? users : users.create;
// If the role the users are moved to is an admin-role, and there's at least 1 (new) admin
// user, we don't have to check for other admin
// users
if ((role.admin_access === true || role.admin_access === 1) && usersThatAreAdded.length > 0) return;
const otherAdminUsers = await this.knex
.count('*', { as: 'count' })
.from('directus_users')
.whereNotIn('directus_users.id', [...userKeys, ...usersThatAreRemoved])
.andWhere({ 'directus_roles.admin_access': true })
.leftJoin('directus_roles', 'directus_users.role', 'directus_roles.id')
.first();
const otherAdminUsersCount = +(otherAdminUsers?.count || 0);
if (otherAdminUsersCount === 0) {
throw new UnprocessableContentError({ reason: `You can't remove the last admin user from the admin role` });
}
return;
}
override async updateOne(key: PrimaryKey, data: Record<string, any>, opts?: MutationOptions): Promise<PrimaryKey> {
try {
if ('users' in data) {
await this.checkForOtherAdminUsers(key, data['users']);
}
} catch (err: any) {
(opts || (opts = {})).preMutationError = err;
}
return super.updateOne(key, data, opts);
}
override async updateBatch(data: Record<string, any>[], opts?: MutationOptions): Promise<PrimaryKey[]> {
const primaryKeyField = this.schema.collections[this.collection]!.primary;
const keys = data.map((item) => item[primaryKeyField]);
const setsToNoAdmin = data.some((item) => item['admin_access'] === false);
try {
if (setsToNoAdmin) {
await this.checkForOtherAdminRoles(keys);
}
} catch (err: any) {
(opts || (opts = {})).preMutationError = err;
}
return super.updateBatch(data, opts);
}
override async updateMany(
keys: PrimaryKey[],
data: Record<string, any>,
opts?: MutationOptions
): Promise<PrimaryKey[]> {
try {
if ('admin_access' in data && data['admin_access'] === false) {
await this.checkForOtherAdminRoles(keys);
}
} catch (err: any) {
(opts || (opts = {})).preMutationError = err;
}
return super.updateMany(keys, data, opts);
}
override async deleteOne(key: PrimaryKey): Promise<PrimaryKey> {
await this.deleteMany([key]);
return key;
}
override async deleteMany(keys: PrimaryKey[]): Promise<PrimaryKey[]> {
const opts: MutationOptions = {};
try {
await this.checkForOtherAdminRoles(keys);
} catch (err: any) {
opts.preMutationError = err;
}
await this.knex.transaction(async (trx) => {
const itemsService = new ItemsService('directus_roles', {
knex: trx,
accountability: this.accountability,
schema: this.schema,
});
const permissionsService = new PermissionsService({
knex: trx,
accountability: this.accountability,
schema: this.schema,
});
const presetsService = new PresetsService({
knex: trx,
accountability: this.accountability,
schema: this.schema,
});
const usersService = new UsersService({
knex: trx,
accountability: this.accountability,
schema: this.schema,
});
// Delete permissions/presets for this role, suspend all remaining users in role
await permissionsService.deleteByQuery(
{
filter: { role: { _in: keys } },
},
{ ...opts, bypassLimits: true }
);
await presetsService.deleteByQuery(
{
filter: { role: { _in: keys } },
},
{ ...opts, bypassLimits: true }
);
await usersService.updateByQuery(
{
filter: { role: { _in: keys } },
},
{
status: 'suspended',
role: null,
},
{ ...opts, bypassLimits: true }
);
await itemsService.deleteMany(keys, opts);
});
return keys;
}
override deleteByQuery(query: Query, opts?: MutationOptions): Promise<PrimaryKey[]> {
return super.deleteByQuery(query, opts);
}
}