-
Notifications
You must be signed in to change notification settings - Fork 355
/
users.ts
1407 lines (1254 loc) · 38 KB
/
users.ts
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
import { intersection } from "lodash";
import { DateTime } from "luxon";
import { Db } from "mongodb";
import {
ALLOWED_USERNAME_CHANGE_TIMEFRAME_DURATION,
COMMENT_REPEAT_POST_DURATION,
DOWNLOAD_LIMIT_TIMEFRAME_DURATION,
SCHEDULED_DELETION_WINDOW_DURATION,
} from "coral-common/constants";
import { Config } from "coral-server/config";
import {
DuplicateEmailError,
DuplicateUserError,
EmailAlreadySetError,
EmailNotSetError,
InternalError,
InvalidCredentialsError,
LocalProfileAlreadySetError,
LocalProfileNotSetError,
PasswordIncorrect,
TokenNotFoundError,
UserAlreadyBannedError,
UserAlreadyPremoderated,
UserAlreadySuspendedError,
UserCannotBeIgnoredError,
UsernameAlreadySetError,
UsernameUpdatedWithinWindowError,
UserNotFoundError,
} from "coral-server/errors";
import logger from "coral-server/logger";
import { Comment, retrieveComment } from "coral-server/models/comment";
import { retrieveManySites } from "coral-server/models/site";
import {
hasFeatureFlag,
linkUsersAvailable,
Tenant,
} from "coral-server/models/tenant";
import {
banUser,
clearDeletionDate,
consolidateUserBanStatus,
consolidateUserPremodStatus,
consolidateUserSuspensionStatus,
createModeratorNote,
createUser,
createUserToken,
deactivateUserToken,
deleteModeratorNote,
findOrCreateUser,
FindOrCreateUserInput,
ignoreUser,
linkUsers,
NotificationSettingsInput,
premodUser,
removeActiveUserSuspensions,
removeUserBan,
removeUserIgnore,
removeUserPremod,
retrieveUser,
retrieveUserWithEmail,
scheduleDeletionDate,
setUserEmail,
setUserLastDownloadedAt,
setUserLocalProfile,
setUserUsername,
suspendUser,
updateUserAvatar,
updateUserEmail,
updateUserModerationScopes,
updateUserNotificationSettings,
updateUserPassword,
updateUserRole,
updateUserUsername,
User,
UserModerationScopes,
verifyUserPassword,
} from "coral-server/models/user";
import {
getLocalProfile,
hasLocalProfile,
hasStaffRole,
} from "coral-server/models/user/helpers";
import { MailerQueue } from "coral-server/queue/tasks/mailer";
import { RejectorQueue } from "coral-server/queue/tasks/rejector";
import { JWTSigningConfig, signPATString } from "coral-server/services/jwt";
import { sendConfirmationEmail } from "coral-server/services/users/auth";
import {
GQLAuthIntegrations,
GQLFEATURE_FLAG,
GQLUSER_ROLE,
} from "coral-server/graph/schema/__generated__/types";
import { AugmentedRedis } from "../redis";
import {
generateAdminDownloadLink,
generateDownloadLink,
} from "./download/token";
import { validateEmail, validatePassword, validateUsername } from "./helpers";
function validateFindOrCreateUserInput(
input: FindOrCreateUser,
options: FindOrCreateUserOptions
) {
if (input.username && !options.skipUsernameValidation) {
validateUsername(input.username);
}
if (input.email) {
validateEmail(input.email);
}
const localProfile = getLocalProfile({ profiles: [input.profile] });
if (localProfile) {
validateEmail(localProfile.id);
validatePassword(localProfile.password);
if (input.email !== localProfile.id) {
throw new Error("email addresses don't match profile");
}
}
}
export type FindOrCreateUser = FindOrCreateUserInput;
export interface FindOrCreateUserOptions {
skipUsernameValidation?: boolean;
}
export async function findOrCreate(
mongo: Db,
tenant: Tenant,
input: FindOrCreateUser,
options: FindOrCreateUserOptions,
now: Date
) {
// Validate the input.
validateFindOrCreateUserInput(input, options);
try {
// Try to find or create the user.
const { user } = await findOrCreateUser(mongo, tenant.id, input, now);
return user;
} catch (err) {
// If this error is related to a duplicate user error, we might have
// encountered a race related to the unique index. We should try once more
// to perform the operation.
if (err instanceof DuplicateUserError) {
// Retry the operation once more, if this operation fails, the error will
// exit this function.
const { user } = await findOrCreateUser(mongo, tenant.id, input, now);
return user;
}
// If this is an error related to a duplicate email, we might be in a
// position where the user can link their accounts. This can only occur if
// the tenant has both local and another social profile enabled.
if (err instanceof DuplicateEmailError && linkUsersAvailable(tenant)) {
// Pull the email address out of the input, and re-try creating the user
// given that. We need to pull the verified property out because we don't
// want to have that embedded in the `...rest` object.
const { email, emailVerified, ...rest } = input;
// Create the user again this time, but associate the duplicate email to
// the user account.
const { user } = await findOrCreateUser(
mongo,
tenant.id,
{ ...rest, duplicateEmail: email },
now
);
return user;
}
// The error wasn't related to a duplicate user or duplicate email error,
// so just re-throw that error again.
throw err;
}
}
export type CreateUser = FindOrCreateUserInput;
export type CreateUserOptions = FindOrCreateUserOptions;
export async function create(
mongo: Db,
tenant: Tenant,
input: CreateUser,
options: CreateUserOptions,
now: Date
) {
// Validate the input.
validateFindOrCreateUserInput(input, options);
if (input.id) {
// Try to check to see if there is a user with the same ID before we try to
// create the user again.
const alreadyFoundUser = await retrieveUser(mongo, tenant.id, input.id);
if (alreadyFoundUser) {
throw new DuplicateUserError();
}
}
if (input.email) {
// Try to lookup the user to see if this user already has an account if they
// do, we can short circuit the database index hit.
const alreadyFoundUser = await retrieveUserWithEmail(
mongo,
tenant.id,
input.email
);
if (alreadyFoundUser) {
throw new DuplicateEmailError(input.email);
}
}
const user = await createUser(mongo, tenant.id, input, now);
// TODO: (wyattjoh) emit that a user was created
// TODO: (wyattjoh) evaluate the tenant to determine if we should send the verification email.
return user;
}
/**
* setUsername will set the username on the User if they don't already have one
* associated with them.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param user User that should get their username changed
* @param username the new username for the User
*/
export async function setUsername(
mongo: Db,
tenant: Tenant,
user: User,
username: string
) {
// We require that the username is not defined in order to use this method.
if (user.username) {
throw new UsernameAlreadySetError();
}
validateUsername(username);
return setUserUsername(mongo, tenant.id, user.id, username);
}
/**
* setEmail will set the email address on the User if they don't already have
* one associated with them.
*
* @param mongo mongo database to interact with
* @param mailer the mailer
* @param tenant Tenant where the User will be interacted with
* @param user User that should get their username changed
* @param email the new email for the User
*/
export async function setEmail(
mongo: Db,
mailer: MailerQueue,
tenant: Tenant,
user: User,
email: string
) {
// We requires that the email address is not defined in order to use this
// method.
if (user.email) {
throw new EmailAlreadySetError();
}
validateEmail(email);
const updatedUser = await setUserEmail(mongo, tenant.id, user.id, email);
// // FIXME: (wyattjoh) evaluate the tenant to determine if we should send the verification email.
// // Send the email confirmation email.
// await sendConfirmationEmail(mailer, tenant, updatedUser, email);
return updatedUser;
}
/**
* setPassword will set the password on the User if they don't already have
* one associated with them. This will allow the User to sign in with their
* current email address and new password if email based authentication is
* enabled. If the User does not have a email address associated with their
* account, this will fail.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param user User that should get their password changed
* @param password the new password for the User
*/
export async function setPassword(
mongo: Db,
tenant: Tenant,
user: User,
password: string
) {
// We require that the email address for the user be defined for this method.
if (!user.email) {
throw new EmailNotSetError();
}
// We also don't allow this method to be used by users that already have a
// local profile.
if (hasLocalProfile(user)) {
throw new LocalProfileAlreadySetError();
}
validatePassword(password);
return setUserLocalProfile(mongo, tenant.id, user.id, user.email, password);
}
/**
* updatePassword will update the password associated with the User. If the User
* does not already have a password associated with their account, it will fail.
* If the User does not have an email address associated with the account, this
* will fail.
*
* @param mongo mongo database to interact with
* @param mailer the mailer
* @param tenant Tenant where the User will be interacted with
* @param user User that should get their password changed
* @param oldPassword the old password for the User
* @param newPassword the new password for the User
*/
export async function updatePassword(
mongo: Db,
mailer: MailerQueue,
tenant: Tenant,
user: User,
oldPassword: string,
newPassword: string
) {
// Validate that the new password is valid.
validatePassword(newPassword);
// We require that the email address for the user be defined for this method.
if (!user.email) {
throw new EmailNotSetError();
}
// We also don't allow this method to be used by users that don't have a local
// profile already.
const profile = getLocalProfile(user, user.email);
if (!profile) {
throw new LocalProfileNotSetError();
}
// Verify that the old password is correct. We'll be using the profile's
// passwordID to ensure we prevent a race.
const passwordVerified = await verifyUserPassword(
user,
oldPassword,
user.email
);
if (!passwordVerified) {
// We throw a PasswordIncorrect error here instead of an
// InvalidCredentialsError because the current user is already signed in.
throw new PasswordIncorrect();
}
const updatedUser = await updateUserPassword(
mongo,
tenant.id,
user.id,
newPassword,
profile.passwordID
);
// If the user has an email address associated with their account, send them
// a ban notification email.
if (updatedUser.email) {
// Send the ban user email.
await mailer.add({
tenantID: tenant.id,
message: {
to: updatedUser.email,
},
template: {
name: "account-notification/password-change",
context: {
// TODO: (wyattjoh) possibly reevaluate the use of a required username.
username: updatedUser.username!,
organizationName: tenant.organization.name,
organizationURL: tenant.organization.url,
organizationContactEmail: tenant.organization.contactEmail,
},
},
});
}
return user;
}
export async function requestAccountDeletion(
mongo: Db,
mailer: MailerQueue,
tenant: Tenant,
user: User,
password: string,
now: Date
) {
if (!user.email) {
throw new EmailNotSetError();
}
const passwordVerified = await verifyUserPassword(user, password, user.email);
if (!passwordVerified) {
// We throw a PasswordIncorrect error here instead of an
// InvalidCredentialsError because the current user is already signed in.
throw new PasswordIncorrect();
}
const deletionDate = DateTime.fromJSDate(now).plus({
seconds: SCHEDULED_DELETION_WINDOW_DURATION,
});
const updatedUser = await scheduleDeletionDate(
mongo,
tenant.id,
user.id,
deletionDate.toJSDate()
);
// TODO: extract out into a common shared formatter
// this is being duplicated everywhere
const formattedDate = Intl.DateTimeFormat(tenant.locale, {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).format(deletionDate.toJSDate());
await mailer.add({
tenantID: tenant.id,
message: {
to: user.email,
},
template: {
name: "account-notification/delete-request-confirmation",
context: {
requestDate: formattedDate,
organizationName: tenant.organization.name,
organizationURL: tenant.organization.url,
},
},
});
return updatedUser;
}
export async function cancelAccountDeletion(
mongo: Db,
mailer: MailerQueue,
tenant: Tenant,
user: User
) {
if (!user.email) {
throw new EmailNotSetError();
}
const updatedUser = await clearDeletionDate(mongo, tenant.id, user.id);
await mailer.add({
tenantID: tenant.id,
message: {
to: user.email,
},
template: {
name: "account-notification/delete-request-cancel",
context: {
organizationName: tenant.organization.name,
organizationURL: tenant.organization.url,
},
},
});
return updatedUser;
}
/**
* createToken will create a Token for the User as well as return a signed Token
* that can be used to authenticate.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param config signing configuration to create the signed token
* @param user User that should get updated
* @param name name of the Token
*/
export async function createToken(
mongo: Db,
tenant: Tenant,
config: JWTSigningConfig,
user: User,
name: string,
now = new Date()
) {
// Create the token for the User!
const result = await createUserToken(mongo, tenant.id, user.id, name, now);
// Sign the token!
const signedToken = await signPATString(
config,
user,
{
// Tokens are issued with the token ID as their JWT ID.
jwtid: result.token.id,
// Tokens are issued with the tenant ID.
issuer: tenant.id,
// Tokens are not valid before the creation date.
notBefore: 0,
},
now
);
return { ...result, signedToken };
}
/**
* deactivateToken will disable the given Token so that it can not be used to
* authenticate any more.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param user User that should get updated
* @param id of the Token to be deactivated
*/
export async function deactivateToken(
mongo: Db,
tenant: Tenant,
user: User,
id: string
) {
if (!user.tokens.find((t) => t.id === id)) {
throw new TokenNotFoundError();
}
return deactivateUserToken(mongo, tenant.id, user.id, id);
}
/**
* updateUsername will update the current users username.
*
* @param mongo mongo database to interact with
* @param mailer mailer queue instance
* @param tenant Tenant where the User will be interacted with
* @param user the User we are updating
* @param username the username that we are setting on the User
*/
export async function updateUsername(
mongo: Db,
mailer: MailerQueue,
tenant: Tenant,
user: User,
username: string,
now: Date
) {
// Validate the username.
validateUsername(username);
const canUpdate = canUpdateLocalProfile(tenant, user);
if (!canUpdate) {
throw new Error("Cannot update profile due to tenant settings");
}
// Get the earliest date that the username could have been edited before to/
// allow it now.
const lastUsernameEditAllowed = DateTime.fromJSDate(now)
.plus({ seconds: -ALLOWED_USERNAME_CHANGE_TIMEFRAME_DURATION })
.toJSDate();
const { history } = user.status.username;
if (history.length > 1) {
// If the last update was made at a date sooner than the earliest edited
// date, then we know that the last edit was conducted within the time-frame
// already.
const lastUpdate = history[history.length - 1];
if (lastUpdate.createdAt > lastUsernameEditAllowed) {
throw new UsernameUpdatedWithinWindowError(lastUpdate.createdAt);
}
}
const updated = await updateUserUsername(
mongo,
tenant.id,
user.id,
username,
user.id
);
if (user.email) {
await mailer.add({
tenantID: tenant.id,
message: {
to: user.email,
},
template: {
name: "account-notification/update-username",
context: {
username: user.username!,
organizationName: tenant.organization.name,
organizationURL: tenant.organization.url,
organizationContactEmail: tenant.organization.contactEmail,
},
},
});
} else {
logger.warn(
{ id: user.id },
"Failed to send email: user does not have email address"
);
}
return updated;
}
/**
* updateUsernameByID will update a given User's username.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param userID the User's ID that we are updating
* @param username the username that we are setting on the User
*/
export async function updateUsernameByID(
mongo: Db,
tenant: Tenant,
userID: string,
username: string,
createdBy: User
) {
return updateUserUsername(mongo, tenant.id, userID, username, createdBy.id);
}
/**
* updateRole will update the given User to the specified role.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param user the user making the request
* @param userID the User's ID that we are updating
* @param role the role that we are setting on the User
*/
export async function updateRole(
mongo: Db,
tenant: Tenant,
user: Pick<User, "id">,
userID: string,
role: GQLUSER_ROLE
) {
if (user.id === userID) {
throw new Error("cannot update your own user role");
}
return updateUserRole(mongo, tenant.id, userID, role);
}
export async function updateModerationScopes(
mongo: Db,
tenant: Tenant,
user: Pick<User, "id">,
userID: string,
moderationScopes: UserModerationScopes
) {
if (!hasFeatureFlag(tenant, GQLFEATURE_FLAG.SITE_MODERATOR)) {
throw new InternalError("feature flag not enabled", {
flag: GQLFEATURE_FLAG.SITE_MODERATOR,
});
}
if (user.id === userID) {
throw new Error("cannot update your own moderation scopes");
}
// Verify that the scopes referenced exist.
if (moderationScopes.siteIDs) {
const sites = await retrieveManySites(
mongo,
tenant.id,
moderationScopes.siteIDs
);
if (sites.some((site) => site === null)) {
throw new Error("site specified does not exist");
}
}
return updateUserModerationScopes(mongo, tenant.id, userID, moderationScopes);
}
/**
* enabledAuthenticationIntegrations returns enabled auth integrations for a tenant
*
* @param tenant Tenant where the User will be interacted with
* @param target whether to filter by stream or admin enabled. defaults to requiring both.
*/
function enabledAuthenticationIntegrations(
tenant: Tenant,
target?: "stream" | "admin"
): string[] {
return Object.keys(tenant.auth.integrations).filter((key: string) => {
const { enabled, targetFilter } = tenant.auth.integrations[
key as keyof GQLAuthIntegrations
];
if (target) {
return enabled && targetFilter[target];
}
return enabled && targetFilter.admin && targetFilter.stream;
});
}
/**
* canUpdateLocalProfile will determine if a user is permitted to update their email address.
*
* @param tenant Tenant where the User will be interacted with
* @param user the User that we are updating
*/
function canUpdateLocalProfile(tenant: Tenant, user: User): boolean {
if (!tenant.accountFeatures.changeUsername) {
return false;
}
if (!hasLocalProfile(user)) {
return false;
}
const streamAuthTypes = enabledAuthenticationIntegrations(tenant, "stream");
// user can update email if local auth is enabled or any integration other than sso is enabled
return (
streamAuthTypes.includes("local") ||
!(streamAuthTypes.length === 1 && streamAuthTypes[0] === "sso")
);
}
/**
* updateEmail will update the current User's email address.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param mailer The mailer queue
* @param config Convict config
* @param signingConfig jwt signing config
* @param user the User that we are updating
* @param emailAddress the email address that we are setting on the User
* @param password the users password for confirmation
*/
export async function updateEmail(
mongo: Db,
tenant: Tenant,
mailer: MailerQueue,
config: Config,
signingConfig: JWTSigningConfig,
user: User,
emailAddress: string,
password: string,
now = new Date()
) {
const email = emailAddress.toLowerCase();
validateEmail(email);
const canUpdate = canUpdateLocalProfile(tenant, user);
if (!canUpdate) {
throw new Error("Cannot update profile due to tenant settings");
}
const passwordVerified = await verifyUserPassword(user, password);
if (!passwordVerified) {
// We throw a PasswordIncorrect error here instead of an
// InvalidCredentialsError because the current user is already signed in.
throw new PasswordIncorrect();
}
const updated = await updateUserEmail(mongo, tenant.id, user.id, email);
await sendConfirmationEmail(
mongo,
mailer,
tenant,
config,
signingConfig,
updated as Required<User>,
now
);
return updated;
}
/**
* updateUserEmail will update the given User's email address. This should not
* trigger and email notifications as it's designed to be used by administrators
* to update a user's email address.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param userID the User's ID that we are updating
* @param email the email address that we are setting on the User
*/
export async function updateEmailByID(
mongo: Db,
tenant: Tenant,
userID: string,
email: string
) {
// Validate the email address.
validateEmail(email);
return updateUserEmail(mongo, tenant.id, userID, email, true);
}
/**
* updateAvatar will update the given User's avatar.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be interacted with
* @param userID the User's ID that we are updating
* @param avatar the avatar that we are setting on the User
*/
export async function updateAvatar(
mongo: Db,
tenant: Tenant,
userID: string,
avatar?: string
) {
return updateUserAvatar(mongo, tenant.id, userID, avatar);
}
/**
* addModeratorNote will add a note to the users account.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be banned on
* @param moderator the Moderator that is creating the note
* @param userID the ID of the User who is the subject of the note
* @param note the contents of the note
* @param now the current time that the note was created
*/
export async function addModeratorNote(
mongo: Db,
tenant: Tenant,
moderator: User,
userID: string,
note: string,
now = new Date()
) {
if (!note || note.length < 1) {
throw new Error("Note cannot be empty");
}
return createModeratorNote(mongo, tenant.id, userID, moderator.id, note, now);
}
/**
* destroyModeratorNote will remove a note from a user
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be banned on
* @param userID id of the user who is the subjet
* @param id id of the note to delete
*/
export async function destroyModeratorNote(
mongo: Db,
tenant: Tenant,
userID: string,
id: string,
createdBy: User
) {
return deleteModeratorNote(mongo, tenant.id, userID, id, createdBy.id);
}
/**
* ban will ban a specific user from interacting with Coral.
*
* @param mongo mongo database to interact with
* @param mailer the mailer
* @param rejector the comment rejector queue
* @param tenant Tenant where the User will be banned on
* @param banner the User that is banning the User
* @param userID the ID of the User being banned
* @param message message to banned user
* @param rejectExistingComments whether all the authors previous comments should be rejected
* @param now the current time that the ban took effect
*/
export async function ban(
mongo: Db,
mailer: MailerQueue,
rejector: RejectorQueue,
tenant: Tenant,
banner: User,
userID: string,
message: string,
rejectExistingComments: boolean,
now = new Date()
) {
// Get the user being banned to check to see if the user already has an
// existing ban.
const targetUser = await retrieveUser(mongo, tenant.id, userID);
if (!targetUser) {
throw new UserNotFoundError(userID);
}
// Check to see if the User is currently banned.
const banStatus = consolidateUserBanStatus(targetUser.status.ban);
if (banStatus.active) {
throw new UserAlreadyBannedError();
}
// Ban the user.
const user = await banUser(mongo, tenant.id, userID, banner.id, message, now);
if (rejectExistingComments) {
await rejector.add({
tenantID: tenant.id,
authorID: userID,
moderatorID: banner.id,
});
}
// If the user has an email address associated with their account, send them
// a ban notification email.
if (user.email) {
// Send the ban user email.
await mailer.add({
tenantID: tenant.id,
message: {
to: user.email,
},
template: {
name: "account-notification/ban",
context: {
// TODO: (wyattjoh) possibly reevaluate the use of a required username.
username: user.username!,
organizationName: tenant.organization.name,
organizationURL: tenant.organization.url,
organizationContactEmail: tenant.organization.contactEmail,
customMessage: (message || "").replace(/\n/g, "<br />"),
},
},
});
}
return user;
}
/**
* premod will premod a specific user.
*
* @param mongo mongo database to interact with
* @param tenant Tenant where the User will be banned on
* @param moderator the User that is banning the User
* @param userID the ID of the User being banned
* @param now the current time that the ban took effect
*/
export async function premod(
mongo: Db,
tenant: Tenant,
moderator: User,
userID: string,
now = new Date()
) {
// Get the user being banned to check to see if the user already has an
// existing ban.
const targetUser = await retrieveUser(mongo, tenant.id, userID);
if (!targetUser) {
throw new UserNotFoundError(userID);
}
// Check to see if the User is currently banned.
const premodStatus = consolidateUserPremodStatus(targetUser.status.premod);
if (premodStatus.active) {
throw new UserAlreadyPremoderated();
}
// Ban the user.
return premodUser(mongo, tenant.id, userID, moderator.id, now);
}
export async function removePremod(
mongo: Db,
tenant: Tenant,
moderator: User,
userID: string,
now = new Date()
) {
// Get the user being suspended to check to see if the user already has an
// existing suspension.