-
-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathusers.js
More file actions
2569 lines (2266 loc) · 106 KB
/
users.js
File metadata and controls
2569 lines (2266 loc) · 106 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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const log = require('npmlog');
const config = require('@zone-eu/wild-config');
const Joi = require('joi');
const ObjectId = require('mongodb').ObjectId;
const tools = require('../tools');
const errors = require('../errors');
const openpgp = require('openpgp');
const BSON = require('bson');
const consts = require('../consts');
const roles = require('../roles');
const imapTools = require('../../imap-core/lib/imap-tools');
const { nextPageCursorSchema, previousPageCursorSchema, sessSchema, sessIPSchema, booleanSchema, metaDataSchema, usernameSchema } = require('../schemas');
const TaskHandler = require('../task-handler');
const { publish, FORWARD_ADDED } = require('../events');
const { ExportStream, ImportStream } = require('../export');
const { successRes, totalRes, pageRes, previousCursorRes, nextCursorRes, quotaRes } = require('../schemas/response/general-schemas');
const { GetUsersResult } = require('../schemas/response/users-schemas');
const { userId } = require('../schemas/request/general-schemas');
const { mongopagingFindWrapper } = require('../mongopaging-find-wrapper');
const FEATURE_FLAGS = ['indexing'];
module.exports = (db, server, userHandler, settingsHandler) => {
const taskHandler = new TaskHandler({ database: db.database });
server.get(
{
name: 'getUsers',
path: '/users',
summary: 'List registered Users',
tags: ['Users'],
validationObjs: {
pathParams: {},
requestBody: {},
queryParams: {
query: Joi.string().empty('').lowercase().max(255).description('Partial match of username or default email address'),
forward: Joi.string().empty('').lowercase().max(255).description('Partial match of a forward email address or URL'),
tags: Joi.string().trim().empty('').max(1024).description('Comma separated list of tags. The User must have at least one to be set'),
requiredTags: Joi.string()
.trim()
.empty('')
.max(1024)
.description('Comma separated list of tags. The User must have all listed tags to be set'),
metaData: booleanSchema.description('If true, then includes metaData in the response'),
internalData: booleanSchema.description('If true, then includes internalData in the response. Not shown for user-role tokens.'),
limit: Joi.number().default(20).min(1).max(250).description('How many records to return'),
next: nextPageCursorSchema,
previous: previousPageCursorSchema,
sess: sessSchema,
ip: sessIPSchema
},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes,
total: totalRes,
page: pageRes,
previousCursor: previousCursorRes,
nextCursor: nextCursorRes,
query: Joi.string().required().description('Partial match of username or default email address'),
results: Joi.array().items(GetUsersResult).required().description('User listing')
}).$_setFlag('objectName', 'GetUsersResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { pathParams, requestBody, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...pathParams,
...requestBody,
...queryParams
});
const result = schema.validate(req.params, {
abortEarly: false,
convert: true,
allowUnknown: true
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
let permission;
let ownOnly = false;
permission = roles.can(req.role).readAny('userlisting');
if (!permission.granted && req.user && ObjectId.isValid(req.user)) {
permission = roles.can(req.role).readOwn('userlisting');
if (permission.granted) {
ownOnly = true;
}
}
// permissions check
req.validate(permission);
let query = result.value.query;
let forward = result.value.forward;
let limit = result.value.limit;
let pageNext = result.value.next;
let pagePrevious = result.value.previous;
let filter = query
? {
$or: [
{
address: {
$regex: tools.escapeRegexStr(query),
$options: ''
}
},
{
unameview: {
$regex: tools.escapeRegexStr(tools.uview(query)),
$options: ''
}
}
]
}
: {};
if (forward) {
filter['targets.value'] = {
$regex: tools.escapeRegexStr(forward),
$options: ''
};
}
let tagSeen = new Set();
let requiredTags = (result.value.requiredTags || '')
.split(',')
.map(tag => tag.toLowerCase().trim())
.filter(tag => {
if (tag && !tagSeen.has(tag)) {
tagSeen.add(tag);
return true;
}
return false;
});
let tags = (result.value.tags || '')
.split(',')
.map(tag => tag.toLowerCase().trim())
.filter(tag => {
if (tag && !tagSeen.has(tag)) {
tagSeen.add(tag);
return true;
}
return false;
});
let tagsview = {};
if (requiredTags.length) {
tagsview.$all = requiredTags;
}
if (tags.length) {
tagsview.$in = tags;
}
if (requiredTags.length || tags.length) {
filter.tagsview = tagsview;
}
if (ownOnly) {
filter._id = new ObjectId(req.user);
}
let total = await db.users.collection('users').countDocuments(filter);
let opts = {
limit,
query: filter,
fields: {
// FIXME: hack to keep _id in response
_id: true,
// FIXME: MongoPaging inserts fields value as second argument to col.find()
projection: {
_id: true,
username: true,
name: true,
address: true,
tags: true,
storageUsed: true,
enabled2fa: true,
autoreply: true,
targets: true,
quota: true,
activated: true,
disabled: true,
suspended: true,
password: true,
encryptMessages: true,
encryptForwarded: true
}
},
// _id gets removed in response if not explicitly set in paginatedField
paginatedField: '_id',
sortAscending: true
};
if (result.value.metaData) {
opts.fields.projection.metaData = true;
}
if (result.value.internalData) {
opts.fields.projection.internalData = true;
}
if (pageNext) {
opts.next = pageNext;
}
if (pagePrevious) {
opts.previous = pagePrevious;
}
let listingWrapper;
try {
listingWrapper = await mongopagingFindWrapper(db.users.collection('users'), opts);
} catch (err) {
res.status(500);
return res.json({
error: 'MongoDB Error: ' + err.message,
code: 'InternalDatabaseError'
});
}
let settings = await settingsHandler.getMulti(['const:max:storage']);
let response = {
success: true,
query,
total,
page: listingWrapper.page,
previousCursor: listingWrapper.previousCursor,
nextCursor: listingWrapper.nextCursor,
results: (listingWrapper.listing.results || []).map(userData => {
let values = {
id: userData._id.toString(),
username: userData.username,
name: userData.name,
address: userData.address,
tags: userData.tags || [],
targets: userData.targets && userData.targets.map(target => target.value).filter(target => target),
enabled2fa: tools.getEnabled2fa(userData.enabled2fa),
autoreply: !!userData.autoreply,
encryptMessages: !!userData.encryptMessages,
encryptForwarded: !!userData.encryptForwarded,
quota: {
allowed: Number(userData.quota) || settings['const:max:storage'],
used: Math.max(Number(userData.storageUsed) || 0, 0)
},
hasPasswordSet: !!userData.password || !!userData.tempPassword,
activated: !!userData.activated,
disabled: !!userData.disabled,
suspended: !!userData.suspended
};
if (userData.metaData) {
values.metaData = tools.formatMetaData(userData.metaData);
}
if (userData.internalData) {
values.internalData = tools.formatMetaData(userData.internalData);
}
return permission.filter(values);
})
};
return res.json(response);
})
);
server.post(
{
path: '/users',
summary: 'Create new user',
name: 'createUser',
tags: ['Users'],
validationObjs: {
requestBody: {
username: usernameSchema
.required()
.description('Username of the User. Dots are allowed but informational only ("user.name" is the same as "username").'),
password: Joi.string()
.max(256)
.allow(false, '')
.required()
.description(
'Password for the account. Set to boolean false to disable password usage for the master scope, Application Specific Passwords would still be allowed'
),
hashedPassword: booleanSchema
.default(false)
.description(
'If true then password is already hashed, so store as is. Supported hashes: pbkdf2, bcrypt ($2a, $2y, $2b), md5 ($1), sha512 ($6), sha256 ($5), argon2 ($argon2d, $argon2i, $argon2id). Stored hashes are rehashed to pbkdf2 on first successful password check.'
),
allowUnsafe: booleanSchema
.default(true)
.description(
'If false then validates provided passwords against Have I Been Pwned API. Experimental, so validation is disabled by default but will be enabled automatically in some future version of WildDuck.'
),
address: Joi.string().email({ tlds: false }).description('Default email address for the User (autogenerated if not set)'),
emptyAddress: booleanSchema
.default(false)
.description(
'If true then do not autogenerate missing email address for the User. Only needed if you want to create a user account that does not have any email address associated'
),
language: Joi.string().empty('').max(20).description('Language code for the User'),
retention: Joi.number().min(0).default(0).description('Default retention time (in ms). Set to 0 to disable'),
name: Joi.string().max(256).description('Name of the User'),
targets: Joi.array()
.items(
Joi.string().email({ tlds: false }),
Joi.string().uri({
scheme: [/smtps?/, /https?/],
allowRelative: false,
relativeOnly: false
})
)
.description(
'An array of forwarding targets. The value could either be an email address or a relay url to next MX server ("smtp://mx2.zone.eu:25") or an URL where mail contents are POSTed to'
),
mtaRelay: Joi.string()
.uri({
scheme: [/smtps?/],
allowRelative: false,
relativeOnly: false
})
.description('An address of an SMTP MTA relay. The value should be a relay url. If specified uses the this relay as the outbound MTA.'),
spamLevel: Joi.number()
.min(0)
.max(100)
.default(50)
.description('Relative scale for detecting spam. 0 means that everything is spam, 100 means that nothing is spam'),
quota: Joi.number().min(0).default(0).description('Allowed quota of the user in bytes'),
recipients: Joi.number().min(0).default(0).description('How many messages per 24 hour can be sent'),
forwards: Joi.number().min(0).default(0).description('How many messages per 24 hour can be forwarded'),
filters: Joi.number().min(0).default(0).description('How many filters are allowed for this account'),
requirePasswordChange: booleanSchema
.default(false)
.description('If true then requires the user to change password, useful if password for the account was autogenerated'),
require2faEnabled: booleanSchema
.default(false)
.description('If true then the account is flagged as requiring 2FA to be enabled'),
imapMaxUpload: Joi.number().min(0).default(0).description('How many bytes can be uploaded via IMAP during 24 hour'),
imapMaxDownload: Joi.number().min(0).default(0).description('How many bytes can be downloaded via IMAP during 24 hour'),
pop3MaxDownload: Joi.number().min(0).default(0).description('How many bytes can be downloaded via POP3 during 24 hour'),
pop3MaxMessages: Joi.number().min(0).default(0).description('How many latest messages to list in POP3 session'),
imapMaxConnections: Joi.number().min(0).default(0).description('How many parallel IMAP connections are allowed'),
receivedMax: Joi.number().min(0).default(0).description('How many messages can be received from MX during 60 seconds'),
fromWhitelist: Joi.array()
.items(Joi.string().trim().max(128))
.description('A list of additional email addresses this user can send mail from. Wildcard is allowed.'),
tags: Joi.array().items(Joi.string().trim().max(128)).description('A list of tags associated with this user'),
addTagsToAddress: booleanSchema.default(false).description('If true then autogenerated address gets the same tags as the user'),
uploadSentMessages: booleanSchema
.default(false)
.description(
'If true then all messages sent through MSA are also uploaded to the Sent Mail folder. Might cause duplicates with some email clients, so disabled by default.'
),
mailboxes: Joi.object()
.keys({
sent: Joi.string()
.empty('')
.regex(/\/{2,}|\/$/, { invert: true }),
trash: Joi.string()
.empty('')
.regex(/\/{2,}|\/$/, { invert: true }),
junk: Joi.string()
.empty('')
.regex(/\/{2,}|\/$/, { invert: true }),
drafts: Joi.string()
.empty('')
.regex(/\/{2,}|\/$/, { invert: true })
})
.description('Optional names for special mailboxes')
.$_setFlag('objectName', 'Mailboxes'),
disabledScopes: Joi.array()
.items(
Joi.string()
.valid(...consts.SCOPES)
.$_setFlag('objectName', 'DisabledScopes')
)
.unique()
.default([])
.description('List of scopes that are disabled for this user ("imap", "pop3", "smtp")'),
metaData: metaDataSchema.label('metaData').description('Optional metadata, must be an object or JSON formatted string'),
internalData: metaDataSchema
.label('internalData')
.description(
'Optional metadata for internal use, must be an object or JSON formatted string of an object. Not available for user-role tokens'
),
pubKey: Joi.string()
.empty('')
.trim()
.regex(/^-----BEGIN PGP PUBLIC KEY BLOCK-----/, 'PGP key format')
.description('Public PGP key for the User that is used for encryption. Use empty string to remove the key'),
encryptMessages: booleanSchema.default(false).description('If true then received messages are encrypted'),
encryptForwarded: booleanSchema.default(false).description('If true then forwarded messages are encrypted'),
featureFlags: Joi.object(Object.fromEntries(FEATURE_FLAGS.map(flag => [flag, booleanSchema.default(false)]))).description(
'Feature flags to specify'
),
sess: sessSchema,
ip: sessIPSchema
},
pathParams: {},
queryParams: {},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes,
id: userId
}).$_setFlag('objectName', 'CreateUserResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { pathParams, requestBody, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...pathParams,
...requestBody,
...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)
});
}
if (result.value.password && !result.value.hashedPassword && !result.value.allowUnsafe) {
try {
const { count } = await tools.checkPwnedPassword(result.value.password);
if (count) {
res.status(403);
return res.json({
error: 'Provided password was found from breached passwords list',
code: 'InsecurePasswordError'
});
}
} catch (E) {
// ignore errors, soft check only
}
}
let permission = roles.can(req.role).createAny('users');
// permissions check
req.validate(permission);
// filter out unallowed fields
let values = permission.filter(result.value);
let targets = values.targets;
let mtaRelay = values.mtaRelay;
if (targets) {
for (let i = 0, len = targets.length; i < len; i++) {
let target = targets[i];
if (!/^smtps?:/i.test(target) && !/^https?:/i.test(target) && target.indexOf('@') >= 0) {
// email
targets[i] = {
id: new ObjectId(),
type: 'mail',
value: target
};
} else if (/^smtps?:/i.test(target)) {
targets[i] = {
id: new ObjectId(),
type: 'relay',
value: target
};
} else if (/^https?:/i.test(target)) {
targets[i] = {
id: new ObjectId(),
type: 'http',
value: target
};
} else {
res.status(400);
return res.json({
error: 'Unknown target type "' + target + '"',
code: 'InputValidationError'
});
}
}
values.targets = targets;
}
if (mtaRelay && /^smtps?:/i.test(mtaRelay)) {
mtaRelay = {
id: new ObjectId(),
type: 'relay',
value: mtaRelay // current mtaRelay string value
};
values.mtaRelay = mtaRelay;
}
if ('pubKey' in req.params && !values.pubKey) {
values.pubKey = '';
}
if (values.tags) {
let tagSeen = new Set();
let tags = values.tags
.map(tag => tag.trim())
.filter(tag => {
if (tag && !tagSeen.has(tag.toLowerCase())) {
tagSeen.add(tag.toLowerCase());
return true;
}
return false;
})
.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
values.tags = tags;
values.tagsview = tags.map(tag => tag.toLowerCase());
}
if (values.address && values.address.indexOf('*') >= 0) {
res.status(400);
return res.json({
error: 'Invalid character in email address: *',
code: 'InputValidationError'
});
}
if (values.fromWhitelist && values.fromWhitelist.length) {
values.fromWhitelist = Array.from(new Set(values.fromWhitelist.map(address => tools.normalizeAddress(address))));
}
if (values.mailboxes) {
let seen = new Set(['INBOX']);
for (let key of ['sent', 'junk', 'trash', 'drafts']) {
if (!values.mailboxes[key]) {
continue;
}
values.mailboxes[key] = imapTools.normalizeMailbox(values.mailboxes[key]);
if (seen.has(values.mailboxes[key])) {
res.status(400);
return res.json({
error: 'Duplicate mailbox name: ' + values.mailboxes[key],
code: 'InputValidationError'
});
}
seen.add(values.mailboxes[key]);
// rename key to use specialUse format ("seen"->"\\Seen")
delete values.mailboxes[key];
values.mailboxes[key.replace(/^./, c => '\\' + c.toUpperCase())] = values.mailboxes[key];
}
}
try {
await getKeyInfo(values.pubKey);
} catch (err) {
res.status(400);
return res.json({
error: 'PGP key validation failed. ' + err.message,
code: 'InputValidationError'
});
}
let user;
try {
user = await userHandler.create(values);
} catch (err) {
log.error('API', err);
res.status(500); // TODO: use response code specific status
return res.json({
error: err.message,
code: err.code,
username: values.username
});
}
if (targets) {
for (let target of targets) {
// log as new redirect targets
try {
await userHandler.logAuthEvent(user, {
action: 'user forward added',
result: 'success',
target: target.value,
protocol: 'API',
sess: values.sess,
ip: values.ip
});
} catch (err) {
// ignore
log.error('API', err);
}
await publish(db.redis, {
ev: FORWARD_ADDED,
user,
type: 'user',
target: target.value
});
}
}
return res.json({
success: !!user,
id: user
});
})
);
server.get(
{
path: '/users/resolve/:username',
summary: 'Resolve ID for a username',
name: 'resolveUser',
tags: ['Users'],
validationObjs: {
requestBody: {},
queryParams: {
sess: sessSchema,
ip: sessIPSchema
},
pathParams: {
username: usernameSchema
.required()
.description(
'Username of the User. Alphanumeric value. Must start with a letter, dots are allowed but informational only ("user.name" is the same as "username")'
)
},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes.example(true),
id: userId.description('Unique ID (24 byte hex)').example('609d201236d1d936948f23b1')
}).$_setFlag('objectName', 'ResolveIdForUsernameResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { pathParams, requestBody, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...pathParams,
...requestBody,
...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)
});
}
// permissions check
req.validate(roles.can(req.role).readAny('users'));
let username = result.value.username;
let userData;
try {
let unameview = '';
if (username.includes('@')) {
unameview = tools.normalizeAddress(username, false, {
removeLabel: true,
removeDots: true
});
} else {
unameview = username.replace(/\./g, '');
}
userData = await db.users.collection('users').findOne(
{
unameview
},
{
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'
});
}
return res.json({
success: true,
id: userData._id.toString()
});
})
);
server.get(
{
path: '/users/:user',
summary: 'Request User information',
name: 'getUser',
tags: ['Users'],
validationObjs: {
requestBody: {},
queryParams: {
sess: sessSchema,
ip: sessIPSchema
},
pathParams: {
user: userId
},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes,
id: userId.description('Users unique ID (24 byte hex)'),
username: Joi.string().required().description('Username of the User'),
name: Joi.string().required().description('Name of the User'),
address: Joi.string().required().description('Main email address of the User'),
retention: Joi.number().description('Default retention time (in ms). Not present if not enabled'),
enabled2fa: Joi.array().items(Joi.string()).required().description('List of enabled 2FA methods'),
autoreply: booleanSchema
.required()
.description('Is autoreply enabled or not (start time may still be in the future or end time in the past)'),
encryptMessages: booleanSchema.required().description('If true then received messages are encrypted'),
encryptForwarded: booleanSchema.required().description('If true then forwarded messages are encrypted'),
pubKey: Joi.string().required().description('Public PGP key for the User that is used for encryption'),
keyInfo: Joi.object({
name: Joi.string().required().description('Name listed in public key'),
address: Joi.string().required().description('E-mail address listed in public key'),
fingerprint: Joi.string().required().description('Fingerprint of the public key')
})
.$_setFlag('objectName', 'KeyInfo')
.required()
.description('Information about public key or false if key is not available'),
metaData: metaDataSchema.required().description('Custom metadata object set for this user'),
internalData: Joi.object({})
.required()
.description('Custom internal metadata object set for this user. Not available for user-role tokens'),
targets: Joi.array().items(Joi.string()).required().description('List of forwarding targets'),
mtaRelay: Joi.string().description('MTA Relay url'),
spamLevel: Joi.number()
.required()
.description('Relative scale for detecting spam. 0 means that everything is spam, 100 means that nothing is spam'),
limits: Joi.object({
quota: quotaRes,
recipients: Joi.object({
allowed: Joi.number().required().description('How many messages per 24 hours can be send'),
used: Joi.number().required().description('How many messages are sent during current 24 hour period'),
ttl: Joi.number().required().description('Time until the end of current 24 hour period')
})
.required()
.$_setFlag('objectName', 'Recipients')
.description('Sending quota'),
filters: Joi.object({
allowed: Joi.number().required().description('How many filters are allowed'),
used: Joi.number().required().description('How many filters have been created')
})
.required()
.$_setFlag('objectName', 'Filters')
.description('Sending quota'),
forwards: Joi.object({
allowed: Joi.number().required().description('How many messages per 24 hours can be forwarded'),
used: Joi.number().required().description('How many messages are forwarded during current 24 hour period'),
ttl: Joi.number().required().description('Time until the end of current 24 hour period')
})
.required()
.$_setFlag('objectName', 'Forwards')
.description('Forwarding quota'),
received: Joi.object({
allowed: Joi.number().required().description('How many messages per 1 hour can be received'),
used: Joi.number().required().description('How many messages are received during current 1 hour period'),
ttl: Joi.number().required().description('Time until the end of current 1 hour period')
})
.required()
.$_setFlag('objectName', 'Received')
.description('Receiving quota'),
imapUpload: Joi.object({
allowed: Joi.number()
.required()
.description(
'How many bytes per 24 hours can be uploaded via IMAP. Only message contents are counted, not protocol overhead.'
),
used: Joi.number().required().description('How many bytes are uploaded during current 24 hour period'),
ttl: Joi.number().required().description('Time until the end of current 24 hour period')
})
.required()
.description('IMAP upload quota')
.$_setFlag('objectName', 'ImapUpload'),
imapDownload: Joi.object({
allowed: Joi.number()
.required()
.description(
'How many bytes per 24 hours can be downloaded via IMAP. Only message contents are counted, not protocol overhead.'
),
used: Joi.number().required().description('How many bytes are downloaded during current 24 hour period'),
ttl: Joi.number().required().description('Time until the end of current 24 hour period')
})
.required()
.description('IMAP download quota')
.$_setFlag('objectName', 'ImapDownload'),
pop3Download: Joi.object({
allowed: Joi.number()
.required()
.description(
'How many bytes per 24 hours can be downloaded via POP3. Only message contents are counted, not protocol overhead.'
),
used: Joi.number().required().description('How many bytes are downloaded during current 24 hour period'),
ttl: Joi.number().required().description('Time until the end of current 24 hour period')
})
.required()
.description('POP3 download quota')
.$_setFlag('objectName', 'Pop3Download'),
imapMaxConnections: Joi.object({
allowed: Joi.number().required().description('How many parallel IMAP connections are permitted'),
used: Joi.number().required().description('How many parallel IMAP connections are currently in use')
})
.description('a')
.$_setFlag('objectName', 'ImapMaxConnections')
})
.required()
.description('Account limits and usage')
.$_setFlag('objectName', 'UserLimits'),
tags: Joi.array().items(Joi.string()).required().description('List of tags associated with the User'),
fromWhitelist: Joi.array()
.items(Joi.string())
.description('A list of additional email addresses this user can send mail from. Wildcard is allowed.'),
disabledScopes: Joi.array()
.items(
Joi.string()
.valid(...consts.SCOPES)
.$_setFlag('objectName', 'DisabledScopes')
)
.unique()
.required()
.default([])
.description('Disabled scopes for this user'),
hasPasswordSet: booleanSchema.required().description('If true then the User has a password set and can authenticate'),
activated: booleanSchema.required().description('Is the account activated'),
disabled: booleanSchema.required().description('If true then the user can not authenticate or receive any new mail'),
suspended: booleanSchema.required().description('If true then the user can not authenticate'),
lastPwnedCheck: Joi.date().description('Date when the last check of password against the Pwned passwords list was done'),
passwordPwned: booleanSchema.required().description('Specifies whether the user password has been found in Pwned passwords list'),
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')
}).$_setFlag('objectName', 'GetUserResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { pathParams, requestBody, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...pathParams,
...requestBody,
...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)
});
}
// permissions check
let permission;
if (req.user && req.user === result.value.user) {
permission = roles.can(req.role).readOwn('users');
} else {
permission = roles.can(req.role).readAny('users');
}
req.validate(permission);
let user = new ObjectId(result.value.user);
let userData;
try {
userData = await db.users.collection('users').findOne({
_id: user
});
} 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 response;
try {
response = await db.redis
.multi()
// sending counters are stored in Redis
// sent messages
.get('wdr:' + userData._id.toString())
.ttl('wdr:' + userData._id.toString())
// forwarded messages
.get('wdf:' + userData._id.toString())
.ttl('wdf:' + userData._id.toString())
// rate limited recipient
.get('rl:rcpt:' + userData._id.toString())
.ttl('rl:rcpt:' + userData._id.toString())
// rate limited imap uploads
.get('iup:' + userData._id.toString())
.ttl('iup:' + userData._id.toString())
// rate limited imap downloads
.get('idw:' + userData._id.toString())
.ttl('idw:' + userData._id.toString())