-
-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathauth.js
More file actions
682 lines (608 loc) · 27.5 KB
/
auth.js
File metadata and controls
682 lines (608 loc) · 27.5 KB
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
'use strict';
const Joi = require('joi');
const ObjectId = require('mongodb').ObjectId;
const tools = require('../tools');
const roles = require('../roles');
const { nextPageCursorSchema, previousPageCursorSchema, sessSchema, sessIPSchema, booleanSchema, usernameSchema } = require('../schemas');
const { successRes } = require('../schemas/response/general-schemas');
const { userId } = require('../schemas/request/general-schemas');
const { mongopagingFindWrapper } = require('../mongopaging-find-wrapper');
module.exports = (db, server, userHandler) => {
server.post(
{
path: '/preauth',
summary: 'Pre-auth check',
name: 'preauth',
description: 'Check if an username exists and can be used for authentication',
tags: ['Authentication'],
validationObjs: {
requestBody: {
username: Joi.alternatives()
.try(usernameSchema, Joi.string().email({ tlds: false }))
.required()
.description('Username or E-mail address'),
scope: Joi.string().default('master').description('Required scope. One of master, imap, smtp, pop3'),
sess: sessSchema,
ip: sessIPSchema
},
queryParams: {},
pathParams: {},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes,
id: userId,
username: Joi.string().required().description('Username of authenticated User'),
address: Joi.string().required().description('Default email address of authenticated User'),
scope: Joi.string().required().description('The scope this authentication is valid for'),
require2fa: Joi.alternatives()
.try(Joi.array().items(Joi.string()), booleanSchema.allow(false))
.required()
.description('List of enabled 2FA mechanisms or false if not required')
}).$_setFlag('objectName', 'PreAuthCheckResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { requestBody, pathParams, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...requestBody,
...pathParams,
...queryParams
});
const result = schema.validate(req.params, {
abortEarly: false,
convert: true
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
let permission = roles.can(req.role).createAny('authentication');
// permissions check
req.validate(permission);
// filter out unallowed fields
result.value = permission.filter(result.value);
let authData, user;
try {
[authData, user] = await userHandler.preAuth(result.value.username, result.value.scope);
} catch (err) {
let response = {
error: err.message,
code: err.code || 'AuthFailed'
};
if (user) {
response.id = user.toString();
}
res.status(403);
return res.json(response);
}
if (!authData) {
let response = {
error: 'Authentication failed',
code: 'AuthFailed'
};
if (user) {
response.id = user.toString();
}
res.status(403);
return res.json(response);
}
let preAuthResponse = {
success: true,
id: authData.user.toString(),
username: authData.username,
address: authData.address,
scope: authData.scope,
require2fa: authData.require2fa
};
res.status(200);
return res.json(permission.filter(preAuthResponse));
})
);
server.post(
{
path: '/authenticate',
summary: 'Authenticate a User',
name: 'authenticate',
tags: ['Authentication'],
validationObjs: {
requestBody: {
username: Joi.alternatives()
.try(usernameSchema, Joi.string().email({ tlds: false }))
.required()
.description('Username or E-mail address'),
password: Joi.string().max(256).required().description('Password'),
protocol: Joi.string().default('API').description('Application identifier for security logs'),
scope: Joi.string()
.default('master')
// token can be true only if scope is master
.when('token', { is: true, then: Joi.valid('master') })
.description('Required scope. One of master, imap, smtp, pop3'),
appId: Joi.string().empty('').uri().description('Optional appId which is the URL of the app'),
token: booleanSchema
.default(false)
.description(
'If true then generates a temporary access token that is valid for this user. Only available if scope is "master". When using user tokens then you can replace user ID in URLs with "me".'
),
sess: sessSchema,
ip: sessIPSchema
},
queryParams: {},
pathParams: {},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes,
id: userId,
username: Joi.string().required().description('Username of authenticated User'),
address: Joi.string().required().description('Default email address of authenticated User'),
scope: Joi.string().required().description('The scope this authentication is valid for'),
require2fa: Joi.alternatives()
.try(Joi.array().items(Joi.string()), booleanSchema.allow(false))
.required()
.description('List of enabled 2FA mechanisms or false if not required'),
require2faEnabled: booleanSchema
.required()
.description('If true then the account is flagged as requiring 2FA to be enabled'),
requirePasswordChange: booleanSchema.required().description('Indicates if account password has been reset and should be replaced'),
token: Joi.string().description(
'If access token was requested then this is the value to use as access token when making API requests on behalf of logged in user.'
),
passwordPwned: booleanSchema.description(
'Indicates whether account password has been found in the list of Pwned passwords and should be replaced'
)
}).$_setFlag('objectName', 'AuthenticateResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { requestBody, pathParams, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...requestBody,
...pathParams,
...queryParams
});
const result = schema.validate(req.params, {
abortEarly: false,
convert: true
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
let permission = roles.can(req.role).createAny('authentication');
// permissions check
req.validate(permission);
// filter out unallowed fields
result.value = permission.filter(result.value);
let meta = {
protocol: result.value.protocol,
sess: result.value.sess,
ip: result.value.ip
};
if (result.value.appId) {
meta.appId = result.value.appId;
}
let authData, user;
try {
[authData, user] = await userHandler.asyncAuthenticate(result.value.username, result.value.password, result.value.scope, meta);
} catch (err) {
let response = {
error: err.message,
code: err.code || 'AuthFailed'
};
if (user) {
response.id = user.toString();
}
res.status(403);
return res.json(response);
}
if (!authData) {
let response = {
error: 'Authentication failed',
code: 'AuthFailed'
};
if (user) {
response.id = user.toString();
}
res.status(403);
return res.json(response);
}
let authResponse = {
success: true,
id: authData.user.toString(),
username: authData.username,
address: authData.address,
scope: authData.scope,
require2fa: authData.require2fa,
require2faEnabled: authData.require2faEnabled,
requirePasswordChange: authData.requirePasswordChange
};
if (authData.passwordPwned) {
authResponse.passwordPwned = authData.passwordPwned;
}
if (result.value.token) {
try {
authResponse.token = await userHandler.generateAuthToken(authData.user);
} catch (err) {
let response = {
error: err.message,
code: err.code || 'AuthFailed',
id: user.toString()
};
res.status(403);
return res.json(response);
}
}
res.status(200);
return res.json(permission.filter(authResponse));
})
);
server.del(
{
path: '/authenticate',
summary: 'Invalidate authentication token',
name: 'invalidateAccessToken',
description: 'This method invalidates currently used authentication token. If token is not provided then nothing happens',
tags: ['Authentication'],
validationObjs: {
requestBody: {},
pathParams: {},
queryParams: {},
response: {
200: {
description: 'Success',
model: Joi.object({ success: successRes }).$_setFlag('objectName', 'SuccessResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
if (req.accessToken) {
try {
await db.redis
.multi()
.del('tn:token:' + req.accessToken.hash)
.exec();
} catch (err) {
// ignore
}
}
return res.json({ success: true });
})
);
server.get(
{
name: 'getAuthlog',
path: '/users/:user/authlog',
summary: 'List authentication Events',
tags: ['Authentication'],
validationObjs: {
requestBody: {},
pathParams: { user: userId },
queryParams: {
action: Joi.string().trim().lowercase().empty('').max(100).description('Limit listing only to values with specific action value'),
limit: Joi.number().default(20).min(1).max(250).description('How many records to return'),
next: nextPageCursorSchema,
previous: previousPageCursorSchema,
filterip: sessIPSchema.description('Limit listing only to values with specific IP address'),
sess: sessSchema,
ip: sessIPSchema
},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes,
action: Joi.string().description('Limit listing only to values with specific action value'),
total: Joi.number().required().description('How many results were found'),
page: Joi.number().required().description('Current page number. Derived from page query argument'),
previousCursor: Joi.alternatives()
.try(Joi.string(), booleanSchema)
.description('Either a cursor string or false if there are not any previous results')
.required(),
nextCursor: Joi.alternatives()
.try(Joi.string(), booleanSchema)
.description('Either a cursor string or false if there are not any next results')
.required(),
results: Joi.array()
.items(
Joi.object({
id: Joi.string().required().description('ID of the event'),
action: Joi.string().required().description('Action identifier'),
result: Joi.string().description('Did the action succeed'),
key: Joi.any().description('Event merge key'),
sess: sessSchema,
ip: sessIPSchema,
created: Joi.date().required().description('Datestring of the Event time'),
protocol: Joi.string().description('Protocol that the authentication was made from'),
requiredScope: Joi.string().description('Scope of the auth'),
target: Joi.string().description('Target value for the action'),
asp: Joi.string().description('Application password ID'),
aname: Joi.string().description('Application password description'),
temporary: booleanSchema.description('Whether the action used a temporary credential'),
filter: Joi.string().description('Filter ID associated with the event'),
credential: Joi.string().description('WebAuthn credential ID'),
appId: Joi.string().description('Optional appId which is the URL of the app'),
require2fa: Joi.alternatives()
.try(Joi.string(), booleanSchema.allow(false))
.description('2FA requirement detail'),
last: Joi.date().required().description('Date of the last update of data'),
events: Joi.number().required().description('Number of times same auth log has occurred'),
source: Joi.string().description('Source of auth. Example: `master` if password auth was used'),
expires: Joi.date()
.required()
.description(
'After this date the given auth log document will not be updated and instead a new one will be created'
)
}).$_setFlag('objectName', 'GetAuthlogResult')
)
.required()
}).$_setFlag('objectName', 'GetAuthlogResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { requestBody, pathParams, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...requestBody,
...pathParams,
...queryParams
});
const result = schema.validate(req.params, {
abortEarly: false,
convert: true,
allowUnknown: false
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
// permissions check
if (req.user && req.user === result.value.user) {
req.validate(roles.can(req.role).readOwn('authentication'));
} else {
req.validate(roles.can(req.role).readAny('authentication'));
}
let user = new ObjectId(result.value.user);
let limit = result.value.limit;
let action = result.value.action;
let ip = result.value.filterip;
let pageNext = result.value.next;
let pagePrevious = result.value.previous;
let userData;
try {
userData = await db.users.collection('users').findOne(
{
_id: user
},
{
projection: {
_id: true
}
}
);
} catch (err) {
res.status(500);
return res.json({
error: 'MongoDB Error: ' + err.message,
code: 'InternalDatabaseError'
});
}
if (!userData) {
res.status(404);
return res.json({
error: 'This user does not exist',
code: 'UserNotFound'
});
}
let filter = { user };
if (ip) {
filter.ip = ip;
}
if (action) {
filter.action = action;
}
let total = await db.users.collection('authlog').countDocuments(filter);
let opts = {
limit,
query: filter,
sortAscending: false
};
if (pageNext) {
opts.next = pageNext;
}
if (pagePrevious) {
opts.previous = pagePrevious;
}
let listingWrapper;
try {
listingWrapper = await mongopagingFindWrapper(db.users.collection('authlog'), opts);
} catch (err) {
res.status(500);
return res.json({
error: 'MongoDB Error: ' + err.message,
code: 'InternalDatabaseError'
});
}
let response = {
success: true,
action,
total,
page: listingWrapper.page,
previousCursor: listingWrapper.previousCursor,
nextCursor: listingWrapper.nextCursor,
results: (listingWrapper.listing.results || []).map(resultData => {
let response = {
id: (resultData._id || '').toString()
};
Object.keys(resultData).forEach(key => {
if (!['_id', 'user'].includes(key)) {
response[key] = resultData[key];
}
});
return response;
})
};
return res.json(response);
})
);
server.get(
{
path: '/users/:user/authlog/:event',
name: 'getAuthlogEvent',
summary: 'Request Event information',
tags: ['Authentication'],
validationObjs: {
requestBody: {},
queryParams: {
sess: sessSchema,
ip: sessIPSchema
},
pathParams: {
user: userId,
event: Joi.string().hex().lowercase().length(24).required().description('ID of the Event')
},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes,
id: Joi.string().required().description('ID of the event'),
action: Joi.string().required().description('Action identifier'),
result: Joi.string().description('Did the action succeed'),
key: Joi.any().description('Event merge key'),
sess: sessSchema,
ip: sessIPSchema,
created: Joi.date().required().description('Datestring of the Event time'),
protocol: Joi.string().description('Protocol that the authentication was made from'),
requiredScope: Joi.string().description('Scope of the auth'),
target: Joi.string().description('Target value for the action'),
asp: Joi.string().description('Application password ID'),
aname: Joi.string().description('Application password description'),
temporary: booleanSchema.description('Whether the action used a temporary credential'),
filter: Joi.string().description('Filter ID associated with the event'),
credential: Joi.string().description('WebAuthn credential ID'),
appId: Joi.string().description('Optional appId which is the URL of the app'),
require2fa: Joi.alternatives()
.try(Joi.string(), booleanSchema.allow(false))
.description('2FA requirement detail'),
last: Joi.date().required().description('Date of the last update of Event'),
events: Joi.number().required().description('Number of times same auth Event has occurred'),
source: Joi.string().description('Source of auth. Example: `master` if password auth was used'),
expires: Joi.date()
.required()
.description('After this date the given auth Event will not be updated and instead a new one will be created')
}).$_setFlag('objectName', 'GetAuthlogEventResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { requestBody, pathParams, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...requestBody,
...pathParams,
...queryParams
});
const result = schema.validate(req.params, {
abortEarly: false,
convert: true,
allowUnknown: false
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
// permissions check
if (req.user && req.user === result.value.user) {
req.validate(roles.can(req.role).readOwn('authentication'));
} else {
req.validate(roles.can(req.role).readAny('authentication'));
}
let user = new ObjectId(result.value.user);
let event = new ObjectId(result.value.event);
let userData;
try {
userData = await db.users.collection('users').findOne(
{
_id: user
},
{
projection: {
_id: true
}
}
);
} catch (err) {
res.status(500);
return res.json({
error: 'MongoDB Error: ' + err.message,
code: 'InternalDatabaseError'
});
}
if (!userData) {
res.status(404);
return res.json({
error: 'This user does not exist',
code: 'UserNotFound'
});
}
let filter = { _id: event, user };
let eventData;
try {
eventData = await db.users.collection('authlog').findOne(filter);
} catch (err) {
res.status(500);
return res.json({
error: 'MongoDB Error: ' + err.message,
code: 'InternalDatabaseError'
});
}
if (!eventData) {
res.status(404);
return res.json({
error: 'Event was not found',
code: 'EventNotFound'
});
}
let response = {
success: true,
id: eventData._id.toString()
};
Object.keys(eventData).forEach(key => {
if (!['_id', 'user'].includes(key)) {
response[key] = eventData[key];
}
});
return res.json(response);
})
);
};