-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathusers.js
399 lines (360 loc) · 13.8 KB
/
users.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
var request = require('request');
var readline = require('readline'),
rl = readline.createInterface(process.stdin, process.stdout);
const fs = require('fs');
var createUserStates = [
{ state: '', prompt: 'Master password'},
{ state: 'MasterPassword', prompt: 'Username' },
{ state: 'UserName', prompt: 'Forename' },
{ state: 'Forename', prompt: 'Phone number' },
{ state: 'PhoneNumber', prompt: 'Password' },
{ state: 'UserPassword', prompt: '' }
];
var deleteUserStates = [
{ state: '', prompt: 'Phone number' },
{ state: 'PhoneNumber', prompt: 'Password' },
{ state: 'UserPassword', prompt: 'User Id' },
{ state: 'UserId', prompt: ''}
];
var addUserToGroupStates = [
{ state: '', prompt: 'AdminUsername' },
{ state: 'AdminUserName', prompt: 'AdminPassword' },
{ state: 'AdminPassword', prompt: 'User Id' },
{ state: 'UserId', prompt: 'Group Id'},
{ state: 'GroupId', prompt: ''}
];
var deleteGroupStates = [
{ state: '', prompt: 'AdminUsername' },
{ state: 'AdminUserName', prompt: 'AdminPassword' },
{ state: 'AdminPassword', prompt: 'Group Id' },
{ state: 'GroupId', prompt: ''}
];
var getUserRemindersStates = [
{ state: '', prompt: 'Username' },
{ state: 'UserName', prompt: 'Password' },
{ state: 'UserPassword', prompt: '' },
];
// The states for creating a user and adding them to a group are the combination
// of the states for creating a user and for adding a user to a group, except that
// the 'userId' state is not used here since the userId is generated during the flow.
var createUserAddToGroupStates = [
{ state: '', prompt: 'Master password'},
{ state: 'MasterPassword', prompt: 'Username' },
{ state: 'UserName', prompt: 'Forename' },
{ state: 'Forename', prompt: 'Phone number' },
{ state: 'PhoneNumber', prompt: 'Password' },
{ state: 'UserPassword', prompt: 'AdminUsername' },
{ state: 'AdminUserName', prompt: 'AdminPassword' },
{ state: 'AdminPassword', prompt: 'Group Id' },
{ state: 'GroupId', prompt: ''}
];
var modeStateArray = [
['create-user', createUserStates],
['delete-user', deleteUserStates],
['delete-group', deleteGroupStates],
['add-user-to-group', addUserToGroupStates],
['create-user-add-to-group', createUserAddToGroupStates],
['get-user-reminders', getUserRemindersStates]
];
if (process.argv.length != 3) {
console.log('One of the follwoing must be supplied:');
modeStateArray.forEach(item => {
console.log(item[0]);
});
process.exit(-1);
}
var statesMap = new Map(modeStateArray);
var mode = process.argv[2];
var activeStates = statesMap.get(mode);
if (!activeStates) {
console.log('One of the follwoing must be supplied:');
modeStateArray.forEach(item => {
console.log(item[0]);
});
process.exit(-1);
}
var baseUrl = 'https://calendar.knilxof.org/api/v2';
var loginRequest = request.defaults({
url: baseUrl + '/login',
json: true
}), createUserRequest,
deleteUserRequest,
getUserRemindersRequest;
var masterPassword;
var adminUserName;
var adminPassword;
var foreName;
var userName;
var userPassword;
var phone;
var userId;
var groupId;
var stateObj = activeStates.shift();
prompt(stateObj.prompt);
rl.prompt();
stateObj = activeStates.shift();
rl.on('line', function(line) {
var userText = line.trim();
switch(stateObj.state) {
case 'MasterPassword':
masterPassword = userText;
break;
case 'UserName':
userName = userText;
break;
case 'Forename':
foreName = userText;
break;
case 'PhoneNumber':
phone = userText;
break;
case 'UserPassword':
userPassword = userText;
break;
case 'AdminUserName':
adminUserName = userText;
break;
case 'AdminPassword':
adminPassword = userText;
break;
case 'UserId':
userId = userText;
break;
case 'GroupId':
groupId = userText;
break;
}
if (stateObj.prompt) {
prompt(stateObj.prompt);
stateObj = activeStates.shift();
rl.prompt();
} else {
toServer().then((result) => {
console.log(result);
console.log('Have a nice day!');
process.exit(0);
});
}
}).on('close', function() {
console.log('Have a great day!');
process.exit(0);
});
function prompt(text) {
rl.setPrompt(text + ': ');
}
function toServer() {
return new Promise((resolve, reject) => {
switch (mode) {
case 'create-user':
login({ username: 'master', password: masterPassword }).then(result => {
var masterToken = result.token;
console.log('Master user token:' + masterToken);
createUserRequest = request.defaults({
url: baseUrl + '/users',
json: true,
headers: {'Authorization': 'Bearer ' + masterToken}
});
var user = {username: phone, forename: foreName, phoneNumber: phone, password: userPassword};
createUser(user).then((result) => {
console.log('User created, id:');
resolve(result.id);
}).catch(error => {
console.log('Error creating user:', error);
});
}).catch(error => {
console.log('Error logging in master user:', error);
});
break;
case 'delete-user':
var user = { username: phone, password: userPassword};
login(user).then(result => {
var token = result.token;
console.log('Token for', user.username + ':', token);
deleteUserRequest = request.defaults({
url: baseUrl + '/users/' + userId,
json: true,
headers: {'Authorization': 'Bearer ' + token}
});
deleteUser(user).then(() => {
console.log('Deleted user with user id:');
resolve(userId);
}).catch(error => {
console.log('Error deleting user:', error);
});
}).catch(error => {
console.log('Error logging in user:', error);
});
break;
case 'delete-group':
var user = { username: adminUserName, password: adminPassword};
login(user).then(result => {
var token = result.token;
console.log('Token for', user.username + ':', token);
deleteGroupRequest = request.defaults({
url: baseUrl + '/groups/' + groupId,
json: true,
headers: {'Authorization': 'Bearer ' + token}
});
deleteGroup(groupId).then(() => {
console.log('Deleted group with id:');
resolve(groupId);
}).catch(error => {
console.log('Error deleting user:', error);
});
}).catch(error => {
console.log('Error logging in user:', error);
});
break;
case 'add-user-to-group':
var admin = { username: adminUserName, password: adminPassword};
login(admin).then(result => {
var token = result.token;
console.log('Token for', admin.username + ':', token);
addToGroupRequest = request.defaults({
baseUrl: baseUrl + '/groups',
json: true,
headers: {'Authorization': 'Bearer ' + token}
});
addToGroup(groupId, userId).then(() => {
resolve('user (' + userId + ') added to group ' + groupId);
}).catch(error => {
console.log('Error adding user to group:', error);
});
}).catch(error => {
console.log('Error logging in admin user:', error);
});
break;
case 'get-user-reminders':
var user = { username: userName, password: userPassword};
login(user).then(result => {
var token = result.token;
console.log('Token for', user.username + ':', token);
getUserRemindersRequest = request.defaults({
baseUrl: baseUrl + '/reminders',
json: true,
headers: {'Authorization': 'Bearer ' + token}
});
getUserReminders().then((result) => {
console.log(result);
}).catch(error => {
console.log('Error getting reminders:', error);
});
}).catch(error => {
console.log('Error logging in admin user:', error);
});
break;
case 'create-user-add-to-group':
login({ username: 'master', password: masterPassword }).then(result => {
var masterToken = result.token;
console.log('Master user token:' + masterToken);
createUserRequest = request.defaults({
url: baseUrl + '/users',
json: true,
headers: {'Authorization': 'Bearer ' + masterToken}
});
var user = {username: phone, forename: foreName, phoneNumber: phone, password: userPassword};
createUser(user).then((result) => {
var userId = result.id;
console.log('User created, id:', userId);
var admin = { username: adminUserName, password: adminPassword};
login(admin).then(result => {
var token = result.token;
console.log('Token for', admin.username + ':', token);
addToGroupRequest = request.defaults({
baseUrl: baseUrl + '/groups',
json: true,
headers: {'Authorization': 'Bearer ' + token}
});
addToGroup(groupId, userId).then(() => {
resolve('user (' + userId + ') added to group ' + groupId);
}).catch(error => {
console.log('Error adding user to group:', error);
});
}).catch(error => {
console.log('Error logging in admin user:', error);
});
}).catch(error => {
console.log('Error creating user:', error);
});
}).catch(error => {
console.log('Error logging in master user:', error);
});
break;
}
});
}
function login(user) {
return new Promise(function(resolve, reject) {
console.log('Logging in user:', JSON.stringify(user), '......');
loginRequest.post(
{
body: user
}
).on('response', function(response) {
onResponse(response, resolve, reject)
});
});
}
function createUser(user) {
console.log('Creating user ' + user.forename + '......');
return new Promise(function(resolve, reject) {
createUserRequest.post(
{
body: user,
}
).on('response', function(response) {
onResponse(response, resolve, reject)
});
});
}
function deleteUser(user) {
console.log('Deleting user ' + user.username + '......');
var user = { username: user.phoneNumber,
currentPassword: userPassword
};
console.log('user information for user being deleted:', JSON.stringify(user));
return new Promise(function(resolve, reject) {
deleteUserRequest.delete(
{
body: user
}
).on('response', function(response) {
onResponse(response, resolve, reject)
});
});
}
function deleteGroup(groupId) {
console.log('Deleting group', groupId + '......');
return new Promise(function(resolve, reject) {
deleteGroupRequest.delete(
{}
).on('response', function(response) {
onResponse(response, resolve, reject)
});
});
}
function addToGroup(groupId, userId) {
console.log('Adding user', userId, 'to group', groupId, '.....');
return new Promise(function(resolve, reject) {
addToGroupRequest.put(
{
url: groupId + '/members/' + userId
}
).on('response', function(response) {
onResponse(response, resolve, reject)
});
});
}
function onResponse(response, resolve, reject) {
var result = {statusCode: response.statusCode};
response.on('data', function(data) {
result.serverData = JSON.parse(data);
}).on('end', function() {
console.log('statusCode:', result.statusCode);
if (result.statusCode < 300) {
resolve(result.serverData || null);
} else {
reject(result.serverData.message);
}
});
}