-
Notifications
You must be signed in to change notification settings - Fork 166
/
DirectoryUsers.ts
261 lines (212 loc) · 7.03 KB
/
DirectoryUsers.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
import type {
Directory,
DirectorySyncResponse,
DirectorySyncRequest,
User,
ApiError,
EventCallback,
IDirectoryConfig,
IUsers,
UserPatchOperation,
} from '../../typings';
import { parseUserPatchRequest, extractStandardUserAttributes, updateRawUserAttributes } from './utils';
import { sendEvent } from '../utils';
import { isConnectionActive } from '../../controller/utils';
import { randomUUID } from 'crypto';
interface DirectoryUsersParams {
directories: IDirectoryConfig;
users: IUsers;
}
export class DirectoryUsers {
private directories: IDirectoryConfig;
private users: IUsers;
private callback: EventCallback | undefined;
constructor({ directories, users }: DirectoryUsersParams) {
this.directories = directories;
this.users = users;
}
public async create(directory: Directory, body: any): Promise<DirectorySyncResponse> {
const userAttributes = extractStandardUserAttributes(body);
// Check if the user already exists
const { data: users } = await this.users.search(userAttributes.email, directory.id);
if (users && users.length > 0) {
return this.respondWithError({ code: 409, message: 'User already exists' });
}
const newUser = {
...userAttributes,
directoryId: directory.id,
raw: 'rawAttributes' in body ? body.rawAttributes : body,
};
if (!newUser.id) {
newUser.id = randomUUID();
}
newUser.raw['id'] = newUser.id;
const { data: user } = await this.users.create(newUser);
await sendEvent('user.created', { directory, user }, this.callback);
return {
status: 201,
data: user?.raw,
};
}
public async get(user: User): Promise<DirectorySyncResponse> {
return {
status: 200,
data: user.raw,
};
}
public async update(directory: Directory, user: User, body: any): Promise<DirectorySyncResponse> {
const userAttributes = extractStandardUserAttributes(body);
const { data: updatedUser } = await this.users.update(user.id, {
...userAttributes,
id: user.id,
raw: 'rawAttributes' in body ? body.rawAttributes : body,
});
await sendEvent('user.updated', { directory, user: updatedUser }, this.callback);
return {
status: 200,
data: updatedUser?.raw,
};
}
public async patch(directory: Directory, user: User, body: any): Promise<DirectorySyncResponse> {
const { Operations } = body as { Operations: UserPatchOperation[] };
let attributes: Partial<User> = {};
let rawAttributes = {};
// There can be multiple update operations in a single request for a user
for (const operation of Operations) {
const parsedAttributes = parseUserPatchRequest(operation);
attributes = {
...attributes,
...parsedAttributes.attributes,
};
rawAttributes = {
...rawAttributes,
...parsedAttributes.rawAttributes,
};
}
const { data: updatedUser } = await this.users.update(user.id, {
...user,
...attributes,
raw: updateRawUserAttributes(user.raw, rawAttributes),
});
await sendEvent('user.updated', { directory, user: updatedUser }, this.callback);
return {
status: 200,
data: updatedUser?.raw,
};
}
public async delete(directory: Directory, user: User): Promise<DirectorySyncResponse> {
await this.users.delete(user.id);
await sendEvent('user.deleted', { directory, user }, this.callback);
return {
status: 200,
data: user.raw,
};
}
public async getAll(queryParams: {
count: number;
startIndex: number;
filter?: string;
directoryId: string;
}): Promise<DirectorySyncResponse> {
const { startIndex, filter, count, directoryId } = queryParams;
let users: User[] | null = [];
let totalResults = 0;
if (filter) {
// Search users by userName
// filter: userName eq "john@example.com"
const { data } = await this.users.search(filter.split('eq ')[1].replace(/['"]+/g, ''), directoryId);
users = data;
totalResults = users ? users.length : 0;
} else {
// Fetch all the existing Users (Paginated)
// At this moment, we don't have method to count the database records.
const { data: allUsers } = await this.users.getAll({ directoryId });
const { data } = await this.users.getAll({ pageOffset: startIndex - 1, pageLimit: count, directoryId });
users = data;
totalResults = allUsers ? allUsers.length : 0;
}
return {
status: 200,
data: {
schemas: ['urn:ietf:params:scim:api:messages:2.0:ListResponse'],
startIndex: startIndex ? startIndex : 1,
totalResults: totalResults ? totalResults : 0,
itemsPerPage: count ? count : 0,
Resources: users ? users.map((user) => user.raw) : [],
},
};
}
private respondWithError(error: ApiError | null) {
return {
status: error ? error.code : 500,
data: {
schemas: ['urn:ietf:params:scim:api:messages:2.0:Error'],
detail: error ? error.message : 'Internal Server Error',
},
};
}
// Handle the request from the Identity Provider and route it to the appropriate method
public async handleRequest(
request: DirectorySyncRequest,
callback?: EventCallback
): Promise<DirectorySyncResponse> {
const { body, query, resourceId: userId, directoryId, apiSecret } = request;
const method = request.method.toUpperCase();
// Get the directory
const { data: directory, error } = await this.directories.get(directoryId);
if (error) {
return this.respondWithError(error);
}
if (!directory) {
return {
status: 200,
data: {},
};
}
if (!isConnectionActive(directory)) {
return {
status: 200,
data: {},
};
}
// Validate the request
if (directory.scim.secret != apiSecret) {
return this.respondWithError({ code: 401, message: 'Unauthorized' });
}
this.callback = callback;
this.users.setTenantAndProduct(directory.tenant, directory.product);
// Get the user
const { data: user } = userId ? await this.users.get(userId) : { data: null };
// Delete password if exists in the body
if (body && 'password' in body) {
delete body['password'];
}
if (userId && !user) {
return this.respondWithError({ code: 404, message: 'User not found' });
}
if (user) {
switch (method) {
case 'GET':
return await this.get(user);
case 'PATCH':
return await this.patch(directory, user, body);
case 'PUT':
return await this.update(directory, user, body);
case 'DELETE':
return await this.delete(directory, user);
}
}
switch (method) {
case 'POST':
return await this.create(directory, body);
case 'GET':
return await this.getAll({
count: query.count as number,
startIndex: query.startIndex as number,
filter: query.filter,
directoryId,
});
}
return this.respondWithError({ code: 404, message: 'Not found' });
}
}