-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathdeleteAllUsers.js
84 lines (76 loc) · 2.4 KB
/
deleteAllUsers.js
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
let token;
const apiUrl = "https://services.cloud.mongodb.com/api/admin/v3.0/groups/5f60207f14dfb25d23101102/apps/6388f860cb722c5a5e002425";
async function adminLogIn() {
const username = context.values.get("adminApiPublicKey");
const apiKey = context.values.get("adminApiPrivateKey");
const response = await context.http.post({
url: "https://services.cloud.mongodb.com/api/admin/v3.0/auth/providers/mongodb-cloud/login",
body: {username, apiKey},
encodeBodyAsJSON: true,
});
const body = EJSON.parse(response.body.text());
return body.access_token;
}
async function fetchUsers() {
const response = await context.http.get({
url: `${apiUrl}/users`,
headers: {"Authorization": [`Bearer ${token}`]}
});
if (response.statusCode !== 200) {
throw new Error(response);
}
return EJSON.parse(response.body.text());
}
async function fetchPendingUsers() {
const response = await context.http.get({
url: `${apiUrl}/user_registrations/pending_users`,
headers: {"Authorization": [`Bearer ${token}`]}
});
if (response.statusCode !== 200) {
throw new Error(response);
}
const users = EJSON.parse(response.body.text());
return users;
}
async function deleteUser({_id}) {
const url = `${apiUrl}/users/${_id}`;
const result = await context.http.delete({
url,
headers: {"Authorization": [`Bearer ${token}`]}
});
if (result.statusCode !== 204) {
throw new Error(result);
}
console.log(_id);
return _id;
}
async function deletePendingUser({_id}) {
const result = await context.http.delete({
url: `${apiUrl}/user_registrations/by_id/${_id}`,
headers: {"Authorization": [`Bearer ${token}`]}
});
if (result.statusCode !== 204) {
throw new Error(result);
}
return _id;
}
exports = async function(arg) {
token = await adminLogIn();
while (true) {
// Users is paginated to 50. Keep calling until all users are deleted.
const users = await fetchUsers();
if (users.length === 0) {
break;
}
console.log(`Deleting ${users.length} user${users.length === 1 ? '' : 's'}.`);
await Promise.all(users.map(deleteUser));
}
while (true) {
const pendingUsers = await fetchPendingUsers();
if (pendingUsers.length === 0) {
break;
}
console.log(`Deleting ${pendingUsers.length} pending user${pendingUsers.length === 1 ? '' : 's'}.`);
return await Promise.all(pendingUsers.map(deletePendingUser));
}
};