-
Notifications
You must be signed in to change notification settings - Fork 31
/
user.ts
1215 lines (1100 loc) · 34.4 KB
/
user.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 validator from "email-validator";
import { Request, RequestHandler, Router } from "express";
import jwt from "jsonwebtoken";
import ms from "ms";
import qs from "qs";
import Stripe from "stripe";
import { v4 as uuid } from "uuid";
import { products } from "../config";
import hash from "../hash";
import logger from "../logger";
import { authorizer, validatePost } from "../middleware";
import {
CreateCustomer,
CreateSubscription,
PasswordResetTokenRequest,
PasswordResetConfirm,
UpdateSubscription,
User,
SuspendUserPayload,
DisableUserPayload,
} from "../schema/types";
import { db } from "../store";
import { InternalServerError, NotFoundError } from "../store/errors";
import { WithID } from "../store/types";
import {
makeNextHREF,
sendgridEmail,
parseFilters,
parseOrder,
recaptchaVerify,
sendgridValidateEmail,
toStringValues,
FieldsMap,
triggerCatalystStreamNuke,
} from "./helpers";
import { EMAIL_VERIFICATION_CUTOFF_DATE } from "../middleware/auth";
import sql from "sql-template-strings";
const adminOnlyFields = ["verifiedAt", "planChangedAt"];
const salesEmail = "sales@livepeer.org";
const infraEmail = "infraservice@livepeer.org";
const freePlan = "prod_O9XuIjn7EqYRVW";
function cleanAdminOnlyFields(fields: string[], obj: Record<string, any>) {
for (const f of fields) {
delete obj[f];
}
}
function cleanUserFields(user: WithID<User>, isAdmin = false) {
if (!user) return user;
user = db.user.cleanWriteOnlyResponse(user);
if (!isAdmin) {
cleanAdminOnlyFields(adminOnlyFields, user);
}
return user;
}
async function findUserByEmail(email: string, useReplica = true) {
// Look for user by lowercase email
const [lowercaseUsers] = await db.user.find(
{ email: email.toLowerCase() },
{ useReplica }
);
if (lowercaseUsers?.length === 1) {
return lowercaseUsers[0];
} else if (lowercaseUsers.length > 1) {
throw new InternalServerError("multiple users found with same email");
}
// Look for user by original email
const [users] = await db.user.find({ email }, { useReplica });
if (!users?.length) {
throw new NotFoundError("user not found");
} else if (users.length > 1) {
throw new InternalServerError("multiple users found with same email");
}
return users[0];
}
async function isEmailRegistered(
email: string,
useReplica = true
): Promise<boolean> {
// Check if lowercase email is already registered
const [lowercaseUsers] = await db.user.find(
{ email: email.toLowerCase() },
{ useReplica }
);
if (lowercaseUsers?.length > 0) return true;
// Check if original email is already registered
const [users] = await db.user.find({ email }, { useReplica });
return users?.length > 0;
}
export const frontendUrl = (
{
headers: { "x-forwarded-proto": proto },
config: { frontendDomain },
}: Request,
path: string
) => `${proto || "https"}://${frontendDomain}${path}`;
export const unsubscribeUrl = (req: Request) => frontendUrl(req, "/contact");
export async function terminateUserStreams(
req: Request,
userId: string
): Promise<void> {
const [streams] = await db.stream.find([
sql`stream.data->>'parentId' IS NULL`,
sql`stream.data->>'userId' = ${userId}`,
]);
for (const stream of streams) {
try {
// we don't want to update all user stream objects, so trigger a manual nuke
await triggerCatalystStreamNuke(req, stream.playbackId);
} catch (err) {
logger.error(
`error suspending stream id=${stream.id} userId=${userId} err=${err}`
);
}
}
}
type StripeProductIDs = CreateSubscription["stripeProductId"];
const defaultProductId: StripeProductIDs = freePlan;
async function getOrCreateCustomer(stripe: Stripe, email: string) {
const existing = await stripe.customers.list({ email });
if (existing.data.length > 0) {
return existing.data[0];
}
return await stripe.customers.create({ email });
}
async function createSubscription(
stripe: Stripe,
stripeProductId: StripeProductIDs,
stripeCustomerId: string,
withPayAsYouGo: boolean
) {
const existing = await stripe.subscriptions.list({
customer: stripeCustomerId,
});
if (existing.data.length > 0) {
return null;
}
const prices = await stripe.prices.list({
lookup_keys: products[stripeProductId].lookupKeys,
});
let payAsYouGoItems = [];
if (withPayAsYouGo) {
const payAsYouGoPrices = await stripe.prices.list({
lookup_keys: products["pay_as_you_go_1"].lookupKeys,
});
payAsYouGoItems = payAsYouGoPrices.data.map((item) => ({
price: item.id,
}));
}
return await stripe.subscriptions.create({
cancel_at_period_end: false,
customer: stripeCustomerId,
items: [
...prices.data.map((item) => ({ price: item.id })),
...payAsYouGoItems,
],
expand: ["latest_invoice.payment_intent"],
});
}
function requireStripe(): RequestHandler {
return (req, res, next) => {
if (!req.stripe) {
return res.status(501).json({ errors: ["stripe not configured"] });
}
return next();
};
}
const app = Router();
app.get("/usage", authorizer({}), async (req, res) => {
let { userId, fromTime, toTime } = toStringValues(req.query);
if (!fromTime || !toTime) {
res.status(400);
return res.json({ errors: ["should specify time range"] });
}
if (!userId || (req.user.admin !== true && req.user.id !== userId)) {
userId = req.user.id;
}
const usageRes = await db.stream.usage(userId, fromTime, toTime, {
useReplica: false,
});
res.status(200);
res.json(usageRes);
});
const fieldsMap: FieldsMap = {
id: `users.ID`,
email: { val: `data->>'email'`, type: "full-text" },
emailValid: { val: `data->'emailValid'`, type: "boolean" },
admin: { val: `data->'admin'`, type: "boolean" },
stripeProductId: `data->>'stripeProductId'`,
};
app.get("/", authorizer({ admin: true }), async (req, res) => {
let { limit, cursor, order, filters } = toStringValues(req.query);
if (isNaN(parseInt(limit))) {
limit = undefined;
}
const query = parseFilters(fieldsMap, filters);
const [output, newCursor] = await db.user.find(query, {
limit,
cursor,
order: parseOrder(fieldsMap, order),
});
res.status(200);
if (output.length > 0 && newCursor) {
res.links({ next: makeNextHREF(req, newCursor) });
}
res.json(db.user.cleanWriteOnlyResponses(output));
});
app.get("/me", authorizer({ allowUnverified: true }), async (req, res) => {
const user = await db.user.get(req.user.id);
res.status(200);
return res.json(cleanUserFields(user, req.user.admin));
});
app.get("/:id", authorizer({ allowUnverified: true }), async (req, res) => {
if (req.user.admin !== true && req.user.id !== req.params.id) {
return res.status(403).json({
errors: ["user can only request information on their own user object"],
});
}
const user = await db.user.get(req.params.id);
res.status(200);
res.json(cleanUserFields(user, req.user.admin));
});
app.delete("/:id", authorizer({ anyAdmin: true }), async (req, res) => {
const { id } = req.params;
const user = await db.user.get(id);
if (!user) {
res.status(404);
return res.json({ errors: ["user not found"] });
}
await db.user.delete(id);
// TODO: remove all streams owned by user
// TODO: remove all assets owned by user
// TODO: remove the stripe account
res.status(204);
res.end();
});
app.post("/", validatePost("user"), async (req, res) => {
const {
email,
password,
firstName,
lastName,
organization,
phone,
recaptchaToken,
} = req.body;
const { selectedPlan } = req.query;
if (req.config.recaptchaSecretKey) {
if (!recaptchaToken) {
res.status(422);
res.json({
errors: ["Recaptcha error: it doesn't exist recaptcha token"],
});
return;
}
try {
const recaptchaScore = await recaptchaVerify(
recaptchaToken,
req.config.recaptchaSecretKey
);
if (recaptchaScore < 0.5) {
res.status(400);
return res.json({
errors: [
`Suspicious behavior detected. Please try again later or contact support.`,
],
});
}
} catch (error) {
res.status(400);
return res.json({
errors: [`Recaptcha error: ${error}`],
});
}
}
const emailValid = validator.validate(email);
if (!emailValid) {
res.status(422);
res.json({ errors: ["invalid email"] });
return;
}
const isEmailRegisteredAlready = await isEmailRegistered(email);
if (isEmailRegisteredAlready) {
res.status(409);
res.json({
errors: [
"email already registered - please sign in instead or check your verification email",
],
});
return;
}
const [hashedPassword, salt] = await hash(password);
const id = uuid();
const emailValidToken = uuid();
// use SendGrid to verify user only if credentials have been provided
let validUser = true;
if (req.config.sendgridApiKey && req.config.supportAddr) {
validUser = false;
}
let admin = false;
const [[oneUser]] = await db.user.find({}, { limit: 1 });
if (!oneUser) {
logger.warn("!!!!!!!!!!!!!!!!!!!");
logger.warn(
`first user detected, promoting new admin userId=${id} email=${email}`
);
logger.warn("!!!!!!!!!!!!!!!!!!!");
admin = true;
}
const lowercaseEmail = email.toLowerCase();
let stripeFields: Partial<User> = {};
if (req.stripe) {
const customer = await getOrCreateCustomer(req.stripe, lowercaseEmail);
const subscription = await createSubscription(
req.stripe,
defaultProductId,
customer.id,
true
);
if (!subscription) {
res.status(400);
res.json({ errors: ["error creating subscription"] });
}
stripeFields = {
stripeCustomerId: customer.id,
stripeCustomerSubscriptionId: subscription.id,
stripeProductId: defaultProductId,
};
}
await db.user.create({
kind: "user",
id: id,
createdAt: Date.now(),
email: lowercaseEmail,
password: hashedPassword,
salt: salt,
admin: admin,
emailValidToken: emailValidToken,
emailValid: validUser,
firstName,
lastName,
organization,
phone,
...stripeFields,
});
const user = cleanUserFields(await db.user.get(id));
if (!validUser && user) {
const {
supportAddr,
sendgridTemplateId,
sendgridApiKey,
sendgridValidationApiKey,
} = req.config;
try {
// This is a test of the Sendgrid email validation API. Remove this
// if we decide not to use it and revert to more basic Sendgrid plan.
sendgridValidateEmail(lowercaseEmail, sendgridValidationApiKey);
// send email verification message to user using SendGrid
await sendgridEmail({
email: lowercaseEmail,
supportAddr,
sendgridTemplateId,
sendgridApiKey,
subject: "Verify your Livepeer Studio Email",
preheader: "Welcome to Livepeer Studio!",
buttonText: "Verify Email",
buttonUrl: frontendUrl(
req,
`/verify?${qs.stringify({
email: lowercaseEmail,
emailValidToken,
selectedPlan,
})}`
),
unsubscribe: unsubscribeUrl(req),
text: [
"Please verify your email address to ensure that you can change your password or receive updates from us.",
].join("\n\n"),
});
} catch (err) {
res.status(400);
return res.json({
errors: [
`error sending confirmation email to ${req.body.email}: error: ${err}`,
],
});
}
}
if (!user) {
res.status(403);
return res.json({ errors: ["user not created"] });
}
let isTest =
process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development";
if (
req.config.requireEmailVerification &&
!user.emailValid &&
!user.admin &&
!isTest &&
user.createdAt > EMAIL_VERIFICATION_CUTOFF_DATE
) {
res.status(403);
return res.json({ errors: ["we just sent you a verification email"] });
}
res.status(201);
res.json(user);
});
const suspensionEmailText = (
emailTemplate: SuspendUserPayload["emailTemplate"]
) => {
switch (emailTemplate) {
case "copyright":
return [
"We were notified that your stream contained illegal or copyrighted content. We have suspended your account.",
"Please note that you cannot use Livepeer to stream copyrighted content. Any copyrighted content will be taken down and your account will be suspended.",
].join("\n\n");
case "disabled":
return "Your account has been disabled. You reached your monthly usage limit for the free tier. Please upgrade your plan.";
default:
return "Your account has been suspended. Please contact us for more information.";
}
};
app.patch(
"/:id/suspended",
validatePost("suspend-user-payload"),
authorizer({ anyAdmin: true }),
async (req, res) => {
const { suspended, emailTemplate } = req.body as SuspendUserPayload;
const { id } = req.params;
if (id === req.user?.id) {
return res.status(400).json({ errors: ["cannot suspend own user"] });
}
const user = await db.user.get(id);
if (!user) {
return res.status(404).json({ errors: ["not found"] });
}
const { email, suspended: wasSuspended } = user;
logger.info(`set user ${id} (${email}) suspended ${suspended}`);
await db.user.update(id, { suspended });
if (suspended) {
terminateUserStreams(req, id).catch((err) => {
logger.error(
`error terminating user streams id=${id} email=${email} err=${err}`
);
});
}
if (suspended && !wasSuspended) {
const {
frontendDomain,
supportAddr,
sendgridTemplateId,
sendgridApiKey,
} = req.config;
try {
await sendgridEmail({
email,
bcc: infraEmail,
supportAddr,
sendgridTemplateId,
sendgridApiKey,
subject: "Account Suspended",
preheader: `Your ${frontendDomain} account has been suspended.`,
buttonText: "Appeal Suspension",
buttonUrl: frontendUrl(req, "/contact"),
unsubscribe: unsubscribeUrl(req),
text: suspensionEmailText(emailTemplate),
});
} catch (err) {
logger.error(
`error sending suspension email to user=${email} err=${err}`
);
}
}
res.status(204);
res.end();
}
);
app.patch(
"/:id/disabled",
validatePost("disable-user-payload"),
authorizer({ anyAdmin: true }),
async (req, res) => {
const { disabled, emailTemplate } = req.body as DisableUserPayload;
const { id } = req.params;
if (id === req.user?.id) {
return res.status(400).json({ errors: ["cannot disable own user"] });
}
const user = await db.user.get(id);
if (!user) {
return res.status(404).json({ errors: ["not found"] });
}
const { email, disabled: wasDisabled } = user;
logger.info(`set user ${id} (${email}) disabled ${disabled}`);
await db.user.update(id, { disabled });
if (disabled) {
terminateUserStreams(req, id).catch((err) => {
logger.error(
`error terminating user streams id=${id} email=${email} err=${err}`
);
});
}
if (disabled && !wasDisabled) {
const {
frontendDomain,
supportAddr,
sendgridTemplateId,
sendgridApiKey,
} = req.config;
try {
console.log(`
sending disabled email to user=${email} emailTemplate=${emailTemplate}
`);
await sendgridEmail({
email,
bcc: infraEmail,
supportAddr,
sendgridTemplateId,
sendgridApiKey,
subject: "Account Disabled",
preheader: `Your ${frontendDomain} account has been disabled. You reached your monthly usage limit.`,
buttonText: "Appeal",
buttonUrl: frontendUrl(req, "/contact"),
unsubscribe: unsubscribeUrl(req),
text: suspensionEmailText("disabled"),
});
} catch (err) {
logger.error(
`error sending disabled email to user=${email} err=${err}`
);
}
}
res.status(204);
res.end();
}
);
app.post("/token", validatePost("user"), async (req, res) => {
const user = await findUserByEmail(req.body.email);
const [hashedPassword] = await hash(req.body.password, user.salt);
if (hashedPassword !== user.password) {
res.status(403);
res.json({ errors: ["incorrect password"] });
return;
}
if (user.suspended) {
res.status(403);
return res.json({ errors: ["user is suspended"] });
}
const token = jwt.sign(
{ sub: user.id, aud: req.config.jwtAudience },
req.config.jwtSecret,
{
algorithm: "HS256",
}
);
let isTest =
process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development";
if (
req.config.requireEmailVerification &&
!user.emailValid &&
!user.admin &&
!isTest &&
user.createdAt > EMAIL_VERIFICATION_CUTOFF_DATE
) {
// Resend the verification email
await sendVerificationEmail(req, user, user.stripeProductId);
res.status(403);
return res.json({
errors: [
"This account has not been verified - please check your inbox for a verification email.",
],
});
}
res.status(201);
res.json({ id: user.id, email: user.email, token: token });
});
app.post("/verify", validatePost("user-verification"), async (req, res) => {
let user = await findUserByEmail(req.body.email);
if (user.emailValidToken === req.body.emailValidToken) {
// alert sales of new verified user
const { supportAddr, sendgridTemplateId, sendgridApiKey } = req.config;
if (req.headers.host.includes("livepeer.studio")) {
try {
// send sales@livepeer.org user verification message using SendGrid
await sendgridEmail({
email: salesEmail,
supportAddr,
sendgridTemplateId,
sendgridApiKey,
subject: `User ${user.email} signed up with Livepeer!`,
preheader: "We have a new verified user",
buttonText: "Log into livepeer",
buttonUrl: frontendUrl(req, "/login"),
unsubscribe: unsubscribeUrl(req),
text: [
`User ${user.email} has signed up and verified their email with Livepeer!`,
].join("\n\n"),
});
} catch (err) {
logger.error(`error sending email to ${salesEmail}: error: ${err}`);
}
}
// return user
user = { ...user, emailValid: true };
await db.user.update(user.id, {
emailValid: true,
verifiedAt: Date.now(),
});
res.status(201);
res.json({ email: user.email, emailValid: user.emailValid });
} else {
res.status(403);
res.json({ errors: ["incorrect user validation token"] });
}
});
// resend verify email
app.post("/verify-email", validatePost("verify-email"), async (req, res) => {
const { selectedPlan } = req.query;
const user = await findUserByEmail(req.body.email);
const emailSent = await sendVerificationEmail(req, user, selectedPlan);
res.status(200).json({ emailSent });
});
async function sendVerificationEmail(req: Request, user: User, selectedPlan) {
const { email, emailValidToken } = user;
const emailValid = validator.validate(email);
if (emailValid || req.user.admin) {
const {
supportAddr,
sendgridTemplateId,
sendgridApiKey,
sendgridValidationApiKey,
} = req.config;
try {
// This is a test of the Sendgrid email validation API. Remove this
// if we decide not to use it and revert to more basic Sendgrid plan.
sendgridValidateEmail(email, sendgridValidationApiKey);
// send email verification message to user using SendGrid
await sendgridEmail({
email,
supportAddr,
sendgridTemplateId,
sendgridApiKey,
subject: "Verify your Livepeer Studio Email",
preheader: "Welcome to Livepeer Studio!",
buttonText: "Verify Email",
buttonUrl: frontendUrl(
req,
`/verify?${qs.stringify({ email, emailValidToken, selectedPlan })}`
),
unsubscribe: unsubscribeUrl(req),
text: [
"Please verify your email address to ensure that you can change your password or receive updates from us.",
].join("\n\n"),
});
return true;
} catch (err) {
return false;
}
}
}
app.post(
"/password/reset",
validatePost("password-reset-confirm"),
async (req, res) => {
const { email, password, resetToken } = req.body as PasswordResetConfirm;
let user = await findUserByEmail(email);
if (!user) {
res.status(404);
return res.json({ errors: [`user email ${email} not found`] });
}
const [tokens] = await db.passwordResetToken.find({
userId: user.id,
});
if (tokens.length < 1) {
res.status(404);
return res.json({ errors: ["Password reset token not found"] });
}
const dbResetToken = tokens.find((t) => t.resetToken === resetToken);
if (!dbResetToken || dbResetToken.expiration < Date.now()) {
res.status(403);
return res.json({
errors: ["incorrect or expired user validation token"],
});
}
// change user password
const [hashedPassword, salt] = await hash(password);
await db.user.update(user.id, {
password: hashedPassword,
salt,
emailValid: true,
});
// delete all password reset tokens from user
await Promise.all(tokens.map((t) => db.passwordResetToken.delete(t.id)));
const userResp = await db.user.get(user.id);
res.status(200).json(cleanUserFields(userResp));
}
);
app.post(
"/password/reset-token",
validatePost("password-reset-token-request"),
async (req, res) => {
const { email } = req.body as PasswordResetTokenRequest;
let user = await findUserByEmail(email);
if (!user) {
res.status(404);
return res.json({ errors: [`user email ${email} not found`] });
}
const id = uuid();
let resetToken = uuid();
await db.passwordResetToken.create({
kind: "password-reset-token",
id: id,
userId: user.id,
resetToken: resetToken,
expiration: Date.now() + ms("48 hours"),
});
const { supportAddr, sendgridTemplateId, sendgridApiKey } = req.config;
try {
await sendgridEmail({
email,
supportAddr,
sendgridTemplateId,
sendgridApiKey,
subject: "Livepeer Password Reset",
preheader: "Reset your Livepeer Password!",
buttonText: "Reset Password",
buttonUrl: frontendUrl(
req,
`/reset-password?${qs.stringify({ email, resetToken })}`
),
unsubscribe: unsubscribeUrl(req),
text: [
"Let's change your password so you can log into Livepeer Studio.",
"Your link is active for 48 hours. After that, you will need to resend the password reset email.",
].join("\n\n"),
});
} catch (err) {
res.status(400);
return res.json({
errors: [`error sending confirmation email to ${email}: error: ${err}`],
});
}
const newToken = db.passwordResetToken.cleanWriteOnlyResponse(
await db.passwordResetToken.get(id)
);
if (newToken) {
res.status(201);
res.json({});
} else {
res.status(403);
res.json({ errors: ["error creating password reset token"] });
}
}
);
app.post(
"/make-admin",
authorizer({ admin: true }),
validatePost("make-admin"),
async (req, res) => {
let user = await findUserByEmail(req.body.email);
await db.user.update(user.id, { admin: req.body.admin });
user = await db.user.get(user.id);
res.status(200).json(cleanUserFields(user, req.user.admin));
}
);
app.post(
"/create-customer",
requireStripe(),
validatePost("create-customer"),
async (req, res) => {
const { email } = req.body as CreateCustomer;
let user = await findUserByEmail(email, false);
let customer: Stripe.Customer;
if (user.stripeCustomerId) {
customer = await req.stripe.customers
.retrieve(user.stripeCustomerId)
.then((c) => (c.deleted !== true ? c : null));
}
if (!customer) {
logger.warn(
`deprecated /create-customer API used. userEmail=${user.email} createdAt=${user.createdAt}`
);
customer = await getOrCreateCustomer(req.stripe, email);
await db.user.update(user.id, {
stripeCustomerId: customer.id,
});
res.status(201);
res.json(customer);
} else {
res.status(400);
res.json({ errors: ["error creating customer"] });
}
}
);
app.post(
"/update-customer-payment-method",
authorizer({ noApiToken: true }),
validatePost("update-customer-payment-method"),
requireStripe(),
async (req, res) => {
const [users] = await db.user.find(
{ stripeCustomerId: req.body.stripeCustomerId },
{ useReplica: false }
);
if (users.length < 1 || users[0].id !== req.user.id) {
res.status(404);
return res.json({ errors: ["user not found"] });
}
let user = users[0];
const paymentMethod = await req.stripe.paymentMethods.attach(
req.body.stripeCustomerPaymentMethodId,
{
customer: req.body.stripeCustomerId,
}
);
const customer = await req.stripe.customers.update(
req.body.stripeCustomerId,
{
invoice_settings: {
default_payment_method: req.body.stripeCustomerPaymentMethodId,
},
}
);
// Update user's payment method
await db.user.update(user.id, {
stripeCustomerPaymentMethodId: req.body.stripeCustomerPaymentMethodId,
ccLast4: paymentMethod.card.last4,
ccBrand: paymentMethod.card.brand,
});
res.json(customer);
}
);
app.post(
"/create-subscription",
validatePost("create-subscription"),
requireStripe(),
async (req, res) => {
const { stripeCustomerId, stripeProductId, stripeCustomerPaymentMethodId } =
req.body as CreateSubscription;
const [users] = await db.user.find(
{ stripeCustomerId: stripeCustomerId },
{ useReplica: false }
);
if (users.length < 1) {
res.status(404);
return res.json({ errors: ["user not found"] });
}
let user = users[0];
if (user.stripeCustomerSubscriptionId) {
const subscription = await req.stripe.subscriptions.retrieve(
user.stripeCustomerSubscriptionId
);
return res.send(subscription);
}
logger.warn(
`deprecated /create-subscription API used. userEmail=${user.email} createdAt=${user.createdAt}`
);
// Attach the payment method to the customer if it exists (free plan doesn't require payment)
if (stripeCustomerPaymentMethodId) {
logger.warn(
`attaching payment method through /create-subscription. userEmail=${user.email} createdAt=${user.createdAt}`
);
try {
const paymentMethod = await req.stripe.paymentMethods.attach(
stripeCustomerPaymentMethodId,
{
customer: stripeCustomerId,
}
);
// Update user's payment method
await db.user.update(user.id, {
stripeCustomerPaymentMethodId: stripeCustomerPaymentMethodId,
ccLast4: paymentMethod.card.last4,
ccBrand: paymentMethod.card.brand,
});
} catch (error) {
return res.status(402).send({ errors: [error.message] });
}
// Change the default invoice settings on the customer to the new payment method
await req.stripe.customers.update(stripeCustomerId, {
invoice_settings: {
default_payment_method: stripeCustomerPaymentMethodId,
},
});
}
// Create the subscription
const subscription = await createSubscription(
req.stripe,
stripeProductId,
stripeCustomerId,
false
);
if (!subscription) {
return res
.status(400)
.send({ errors: ["could not create subscription"] });
}
// Update user's product and subscription id in our db
await db.user.update(user.id, {
stripeProductId,
stripeCustomerSubscriptionId: subscription.id,
});
res.send(subscription);
}
);