-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
445 lines (382 loc) · 12.5 KB
/
index.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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
const axios = require('axios');
const inquirer = require('inquirer').default;
const fs = require('node:fs');
require('dotenv').config();
const DOMAIN = process.env.DOMAIN;
const CLIENT_ID = process.env.CLIENT_ID;
const SECRET = process.env.SECRET;
const MONTHS = parseInt(process.env.INACTIVEM) || 0;
const DAYS = parseInt(process.env.INACTIVED) || 0;
const LIMIT = 850;
async function getToken() {
try {
const response = await axios.post(`https://${DOMAIN}/oauth/token`, {
client_id: CLIENT_ID,
client_secret: SECRET,
audience: `https://${DOMAIN}/api/v2/`,
grant_type: 'client_credentials',
});
return response.data.access_token;
} catch (error) {
console.error('Error getting access token:', error.response ? error.response.data : error.message);
}
}
async function GetAll(Token) {
try {
let users = [];
let page = 0;
const perPage = 50;
let hasMore = true;
while (hasMore) {
const response = await axios.get(`https://${DOMAIN}/api/v2/users`, {
headers: {
Authorization: `Bearer ${Token}`,
},
params: {
page: page,
per_page: perPage,
},
});
users = users.concat(response.data);
// console.log(`Fetched page ${page + 1} with ${response.data.length} users`);
hasMore = response.data.length === perPage;
page++;
}
// console.log(`Total users fetched: ${users.length}`);
return users;
} catch (error) {
console.error('Error fetching users:', error.response ? error.response.data : error.message);
}
}
async function ListAll() {
const Token = await getToken();
if (!Token) return;
const users = await GetAll(Token);
if (!users || users.length === 0) {
console.log('No users found.');
return;
}
console.log('List of Users:');
users.forEach(user => {
console.log(`- ${user.email} (User ID: ${user.user_id}, Logins Count: ${user.logins_count !== undefined ? user.logins_count : 'Not Available'})`);
});
}
async function NoLogins() {
const Token = await getToken();
if (!Token) return;
const users = await GetAll(Token);
if (!users || users.length === 0) {
console.log('No users found.');
return;
}
const NoLogins = users.filter(user => user.logins_count === undefined || user.logins_count === 0);
if (NoLogins.length === 0) {
console.log('No users with zero logins found.');
} else {
console.log('List of Users with 0 Logins:');
NoLogins.forEach(user => {
console.log(`- ${user.email} (User ID: ${user.user_id})`);
});
}
}
async function ListInactive() {
const Token = await getToken();
if (!Token) return;
const users = await GetAll(Token);
if (!users || users.length === 0) {
console.log('No users found.');
return;
}
if (MONTHS === 0 && DAYS === 0) {
console.warn('Inactive Months and Days are not set. Please set at least one.');
return;
}
let cutoffDate = new Date();
if (MONTHS > 0) {
cutoffDate.setMonth(cutoffDate.getMonth() - MONTHS);
}
if (DAYS > 0) {
cutoffDate.setDate(cutoffDate.getDate() - DAYS);
}
const inactiveUsers = users.filter(user => {
const lastLogin = user.last_login ? new Date(user.last_login) : null;
return !lastLogin || lastLogin < cutoffDate;
});
if (inactiveUsers.length === 0) {
console.log('No inactive users found.');
} else {
console.log(`Inactive Users: ${inactiveUsers.length}`);
inactiveUsers.forEach(user => {
const lastLogin = user.last_login ? new Date(user.last_login) : null;
const inactiveDuration = lastLogin ? Math.floor((Date.now() - lastLogin) / (1000 * 60 * 60 * 24)) : 'N/A';
console.log(`- ${user.email} (User ID: ${user.user_id}, Inactive for: ${inactiveDuration} days)`);
});
}
}
async function DeleteUser(Token, userId) {
try {
await axios.delete(`https://${DOMAIN}/api/v2/users/${userId}`, {
headers: {
Authorization: `Bearer ${Token}`,
},
});
console.log(`Deleted user: ${userId}`);
} catch (error) {
console.error(`Error deleting user ${userId}:`, error.response ? error.response.data : error.message);
}
}
async function DeleteAll() {
const Token = await getToken();
if (!Token) return;
const users = await GetAll(Token);
if (!users || users.length === 0) {
console.log('No users found.');
return;
}
if (users.length <= 1) {
console.log('You cannot delete all users. At least one user must remain.');
return;
}
const answer = await inquirer.prompt([
{
type: 'confirm',
name: 'confirm',
message: 'Are you sure you want to delete all users? This action is irreversible.',
default: false,
},
]);
if (answer.confirm) {
const ToDelete = users.slice(0, users.length - 1);
for (const user of ToDelete) {
await DeleteUser(Token, user.user_id);
await new Promise(resolve => setTimeout(resolve, LIMIT));
}
console.log('All users deleted successfully except for one.');
} else {
console.log('Action cancelled. No users were deleted.');
}
}
async function DeleteNoLogins() {
const Token = await getToken();
if (!Token) return;
const users = await GetAll(Token);
if (!users || users.length === 0) {
console.log('No users found.');
return;
}
const NoLogins = users.filter(user => user.logins_count === undefined || user.logins_count === 0);
if (NoLogins.length === 0) {
console.log('No users with zero logins found.');
} else {
console.log('List of Users with 0 Logins:');
NoLogins.forEach(user => {
console.log(`- ${user.email} (User ID: ${user.user_id})`);
});
const answer = await inquirer.prompt([
{
type: 'confirm',
name: 'confirm',
message: 'Are you sure you want to delete all users with no logins? This action is irreversible.',
default: false,
},
]);
if (answer.confirm) {
for (const user of NoLogins) {
await DeleteUser(Token, user.user_id);
}
console.log('All users with no logins deleted successfully.');
} else {
console.log('Action cancelled. No users were deleted.');
}
}
}
async function DeleteInactive() {
const Token = await getToken();
if (!Token) return;
const users = await GetAll(Token);
if (!users || users.length === 0) {
console.log('No users found.');
return;
}
const cutoffDate = new Date();
if (MONTHS > 0) {
cutoffDate.setMonth(cutoffDate.getMonth() - MONTHS);
}
if (DAYS > 0) {
cutoffDate.setDate(cutoffDate.getDate() - DAYS);
}
const inactiveUsers = users.filter(user => {
const lastLogin = user.last_login ? new Date(user.last_login) : null;
return !lastLogin || lastLogin < cutoffDate;
});
const inactiveCount = inactiveUsers.length;
if (inactiveCount === 0) {
console.log('No inactive users found.');
} else {
console.log(`Fetched ${Math.ceil(users.length / 50)} pages with ${users.length} users`);
console.log(`Inactive Users: ${inactiveCount}`);
console.log('List of Inactive Users:');
inactiveUsers.forEach(user => {
const lastLogin = user.last_login ? new Date(user.last_login) : null;
const inactiveDuration = lastLogin ? Math.floor((Date.now() - lastLogin) / (1000 * 60 * 60 * 24)) : 'N/A';
console.log(`- ${user.email} (User ID: ${user.user_id}, Inactive for: ${inactiveDuration} days)`);
});
const answer = await inquirer.prompt([
{
type: 'confirm',
name: 'confirm',
message: 'Are you sure you want to delete all inactive users? This action is irreversible.',
default: false,
},
]);
if (answer.confirm) {
console.log(`Deleting ${inactiveCount} inactive users...`);
for (const user of inactiveUsers) {
await DeleteUser(Token, user.user_id);
}
console.log('All inactive users deleted successfully.');
} else {
console.log('Action cancelled. No users were deleted.');
}
}
}
async function AddUser() {
const Token = await getToken();
if (!Token) return;
let email;
while (true) {
if (!email) {
const emailInput = await inquirer.prompt([
{ type: 'input', name: 'email', message: 'Enter the email of the user:' },
]);
email = emailInput.email;
}
const passwordInput = await inquirer.prompt([
{ type: 'input', name: 'password', message: 'Enter the password for the user:' },
]);
const password = passwordInput.password;
try {
const response = await axios.post(`https://${DOMAIN}/api/v2/users`, {
email: email,
password: password,
connection: process.env.CONNECTION,
}, {
headers: {
Authorization: `Bearer ${Token}`,
},
});
console.log(`Added user: ${response.data.email} (User ID: ${response.data.user_id})`);
break;
} catch (error) {
if (error.response && error.response.data && error.response.data.message.includes('PasswordStrengthError')) {
console.log('Password is too weak. Please try again.');
} else {
console.error(`Error adding user:`, error.response ? error.response.data : error.message);
break;
}
}
}
}
async function ImportUsers() {
const Token = await getToken();
if (!Token) return;
fs.readFile('./data/users.json', 'utf8', async (err, data) => {
if (err) {
console.error('Error reading users.json:', err);
return;
}
try {
const users = JSON.parse(data);
for (const user of users) {
await axios.post(`https://${DOMAIN}/api/v2/users`, {
email: user.email,
password: user.password,
connection: process.env.CONNECTION,
}, {
headers: {
Authorization: `Bearer ${Token}`,
},
});
console.log(`Imported user: ${user.email}`);
await new Promise(resolve => setTimeout(resolve, LIMIT));
}
} catch (error) {
console.error(`Error importing users:`, error.response ? error.response.data : error.message);
}
});
}
async function ChooseList() {
const option = await inquirer.prompt([
{
type: 'list',
name: 'list',
message: 'What do you want to do?',
choices: ['List All Users', 'List Users with No Logins', 'List Inactive Accounts', 'Back'],
},
]);
if (option.list === 'List All Users') {
await ListAll();
} else if (option.list === 'List Users with No Logins') {
await NoLogins();
} else if (option.list === 'List Inactive Accounts') {
await ListInactive();
} else if (option.list === 'Back') {
await Main();
}
}
async function ChooseDelete() {
const option = await inquirer.prompt([
{
type: 'list',
name: 'deleteOption',
message: 'What do you want to delete?',
choices: ['Delete All Users', 'Delete Users with No Logins', 'Delete Inactive Users', 'Back'],
},
]);
if (option.deleteOption === 'Delete All Users') {
await DeleteAll();
} else if (option.deleteOption === 'Delete Users with No Logins') {
await DeleteNoLogins();
} else if (option.deleteOption === 'Delete Inactive Users') {
await DeleteInactive();
} else if (option.deleteOption === 'Back') {
await Main();
}
}
async function ChooseAdd() {
const option = await inquirer.prompt([
{
type: 'list',
name: 'addOption',
message: 'What do you want to do?',
choices: ['Add User', 'Import Users', 'Back'],
},
]);
if (option.addOption === 'Add User') {
await AddUser();
} else if (option.addOption === 'Import Users') {
await ImportUsers();
} else if (option.addOption === 'Back') {
await Main();
}
}
async function Main() {
const option = await inquirer.prompt([
{
type: 'list',
name: 'list',
message: 'What do you want to do?',
choices: ['List Users', 'Delete Users', 'Add Users', 'Exit'],
},
]);
if (option.list === 'List Users') {
await ChooseList();
} else if (option.list === 'Delete Users') {
await ChooseDelete();
} else if (option.list === 'Add Users') {
await ChooseAdd();
} else {
console.log('Exiting...');
}
}
Main();