-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuserService.js
850 lines (800 loc) · 23.2 KB
/
userService.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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
const mongoose = require("mongoose");
const dao = require("../dao/baseDao");
const userDao = require("./userDao");
const bcrypt = require("bcryptjs");
const s3Bucket = require("../common/refrence");
const jwt = require("jsonwebtoken");
const userModel = require("../generic/models/userModel");
const userMaster = mongoose.model("tb_userMaster", userModel.userMasterSchema);
const blackListModel = require("../generic/models/blackListTokenModel");
const blackListMaster = mongoose.model(
"tb_blackListToken",
blackListModel.blackListMasterSchema
);
const userMapper = require("./userMapper");
const userConst = require("./userConstants");
const constants = require("../constants");
const fs = require("fs");
const appUtils = require("../appUtils");
// User Login
function loginUser(req) {
let userMasterDao = new dao(userMaster);
let query = {
tb_user_email: req.body.usr_email,
};
return userMasterDao
.findOne(query)
.then(async (result) => {
if (result) {
if (result.tb_user_email_verified == true) {
if (result.tb_user_set_password == true) {
let passwordMatch = await bcrypt.compareSync(
req.body.usr_pass,
result.tb_user_password
);
if (passwordMatch) {
result = result.toObject();
let token = jwt.sign(
{
_id: result._id,
},
process.env.user_secret,
{
expiresIn: "1 day",
}
);
let update = {
$set: {
tb_user_device_id: req.body.usr_device_id,
tb_user_fcm_token: req.body.usr_fcm_token,
},
};
await userMasterDao
.findOneAndUpdate(query, update, { new: true })
.then(async (data) => {
if (data) {
console.log("FCM Token and Device Id Saved");
} else {
console.log("Failed to Save FCM Token and Device Id");
}
});
let returnObj = {
user: result,
token: token,
};
return await returnObj;
} else {
return { code: 2, result };
}
} else {
return { code: 3, result };
}
} else {
return { code: 4, result };
}
} else {
return { code: 1, result };
}
})
.catch((err) => {
return err;
});
}
// User Signup Step 1
function signupUserStep1(req) {
let query = {
$or: [
{ tb_user_email: req.body.tb_user_email },
{ tb_user_mobile: req.body.tb_user_mobile },
],
};
return userDao.getProfile(query).then((result) => {
if (!result) {
var verificationCode = Math.floor(
Math.random() * (999999 - 100000) + 100000
);
let verificationCodeForSms = Math.floor(
Math.random() * (999999 - 100000) + 100000
);
var mailOptions = {
from: process.env.gmailAccount,
to: req.body.tb_user_email,
subject: "Email Verification",
html: `<p>Hi,</p><p>Please Verify Your Email.</p><p>Verification Code: <b>${verificationCode}</b>.</p>`,
};
let obj = {
tb_user_firstName: req.body.tb_user_firstName,
tb_user_lastName: req.body.tb_user_lastName,
tb_user_email: req.body.tb_user_email,
tb_user_mobile: req.body.tb_user_mobile,
tb_user_verificationCode: verificationCode,
tb_user_verificationCodeForSms: verificationCodeForSms,
tb_user_verificationCodeTime: Date.now(),
};
return userDao.signupUserStep1(obj).then(async (data) => {
if (data) {
console.log("User Created Successfully");
await appUtils.sendMail(mailOptions);
let message =
userConst.MESSAGE.smsVerifiactionMessage + verificationCodeForSms;
await appUtils.sendSms({
mobileNumber: req.body.tb_user_mobile,
message,
});
let responseObj = Object.assign({}, data._doc);
delete responseObj.tb_user_verificationCode;
delete responseObj.tb_user_verificationCodeTime;
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.successUserCreated,
responseObj
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.userCreateError
);
}
});
} else {
if (result.tb_user_email == req.body.tb_user_email) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.userExist
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.mobileExist
);
}
}
});
}
// User Signup Step 2
async function signupUserStep2(req) {
let query = {
_id: req.params.userId,
};
return userDao.getProfile(query).then((result) => {
if (result) {
if (
result.tb_user_verificationCode == req.body.tb_user_verificationCode
) {
if (
result.tb_user_verificationCodeForSms ==
req.body.tb_user_mobileVerificationCode
) {
let oldTime = result.tb_user_verificationCodeTime + 120000;
if (oldTime >= Date.now()) {
let update = {
tb_user_email_verified: true,
};
return userDao.signupUser(query, update).then((data) => {
if (data) {
data = data.toObject();
delete data.tb_user_verificationCode;
delete data.tb_user_password;
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.emailVerified,
data
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.emailNotVerified
);
}
});
} else {
return userMapper.responseMapping(
userConst.CODE.NotImplemented,
userConst.MESSAGE.otpExpired
);
}
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.invalidMobileOTP
);
}
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.invalidOTP
);
}
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.notExist
);
}
});
}
// User Signup Step 3
async function signupUserStep3(req) {
let query = {
_id: req.params.userId,
tb_user_email_verified: true,
};
let password = await bcrypt.hashSync(req.body.tb_user_password, 10);
let update = {
tb_user_password: password,
tb_user_set_password: true,
tb_user_device_id: req.body.tb_user_device_id,
tb_user_fcm_token: req.body.tb_user_fcm_token,
};
let token = jwt.sign(
{
_id: req.params.userId,
},
process.env.user_secret,
{
expiresIn: "1 day",
}
);
return userDao.signupUser(query, update).then((data) => {
if (data) {
console.log("Set Password Successfully");
data = data.toObject();
delete data.tb_user_verificationCode;
delete data.tb_user_password;
let returnObj = {
user: data,
token: token,
};
return userMapper.successLoginMapper(returnObj);
} else {
return userMapper.passwordNotSetMapper();
}
});
}
// Forget Password
async function forgetPassword(req) {
let query = {
tb_user_email: req.body.usr_email,
};
return userDao.getProfile(query).then(async (data) => {
if (data) {
var randomPassword = Math.random().toString(36).slice(-8);
var passwordUrl = process.env.passwordUrl;
var isFromForgotPassword = true;
var Url = `${passwordUrl}=${randomPassword}&email=${req.body.usr_email}&isFromForgotPassword=${isFromForgotPassword}`;
let usr_pass = await bcrypt.hashSync(randomPassword, 10);
let update = {
tb_user_password: usr_pass,
tb_user_passwordResetTime: Date.now(),
};
return userDao.forgotPassword(query, update).then(async (result) => {
if (result) {
var mailOptions = {
from: "[email protected]",
to: req.body.usr_email,
subject: "Reset Password",
html: `<p>Hi,</p><p>You recently requested to reset your password.Click the button below to reset it</p><a href='${Url}'>Click Me</a>`,
};
await appUtils.sendMail(mailOptions);
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.successEmailSend,
result
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.inValidMailId
);
}
});
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.notExist
);
}
});
}
// Reset Password
function resetPassword(req) {
let query = {
tb_user_email: req.body.usr_email,
};
return userDao.getProfile(query).then(async (data) => {
if (data) {
let passwordMatch = await bcrypt.compareSync(
req.body.usr_pass,
data.tb_user_password
);
if (passwordMatch) {
let newPassword = await bcrypt.hashSync(req.body.new_usr_pass, 10);
let update = {
tb_user_password: newPassword,
};
return userDao.resetPassword(query, update).then(async (result) => {
if (result) {
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.successResetPassword,
result
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.errorInResetPassword
);
}
});
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.passwordResetLinkExpired
);
}
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.notExist
);
}
});
}
// Get Profile
function getProfile(req) {
let query = {
_id: req.params.userId,
};
return userDao.getProfile(query).then(async (result) => {
if (result) {
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.successGetProfileDetail,
result
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.failedGetProfileDetail
);
}
});
}
// Edit Profile
async function editProfile(req) {
let profilePicture = "";
let query = {
_id: req.params.userId,
};
if (req.body.usr_photo) {
profilePicture = req.body.usr_photo;
}
let update = {
tb_user_photo: profilePicture,
tb_user_firstName: req.body.usr_firstName,
tb_user_lastName: req.body.usr_lastName,
tb_user_mobile: req.body.usr_mobile,
};
return userDao
.updateProfile(query, update)
.then(async (result) => {
if (result) {
return await userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.successProfileEdit,
result
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.failedEditProfile
);
}
})
.catch((err) => {
return userMapper.responseMapping(
userConst.CODE.DataNotFound,
userConst.MESSAGE.notExist
);
});
}
async function editProfilePicture(req, res) {
return await new Promise(async (resolve, reject) => {
var re = /(?:\.([^.]+))?$/;
let filename = req.params.userId+'.'+re.exec(req.files.usr_photo.name)[1];
let path = __dirname + "/images/" + filename;
await req.files.usr_photo.mv(path, function (err) {
if (err) {
console.log(err);
reject(
userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.failedEditProfilePicture
)
);
} else {
resolve(
userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.successProfilePictureEdit,
"/image/"+filename
)
);
}
});
});
}
function logoutUser(req) {
let token = req.headers.authorization;
let query = {
token: token,
};
return userDao.getBlacklistToken(query).then((result) => {
if (result || result == null) {
return userDao.addBlacklistToken(query).then(async (tokenResult) => {
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.successLogout,
tokenResult
);
});
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.failedLogout
);
}
});
}
/**
* Get all notifications for user
*/
function getNotificationsList(req) {
let userId = req.params.userId;
if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.InvalidDetails
);
} else {
let query = {
receiverId: mongoose.Types.ObjectId(userId),
};
return userDao
.getUserNotifications(query)
.then(async (result) => {
await userDao.updateNotification(query, { isRead: true });
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.Success,
result
);
})
.catch((e) => {
console.log({ e });
return userMapper.responseMapping(
userConst.CODE.INTRNLSRVR,
userConst.MESSAGE.internalServerError
);
});
}
}
/**for update preference */
function updatePreferences(req) {
let userId = req.params.userId;
if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.InvalidDetails
);
} else {
let userQuery = {
_id: userId,
tb_user_isActive: true,
};
return userDao.getProfile(userQuery).then((userDetails) => {
if (!userDetails) {
return userMapper.responseMapping(
userConst.CODE.DataNotFound,
userConst.MESSAGE.InvalidCredentials
);
} else {
return userDao
.updateProfile(userQuery, req.body)
.then((userUpdated) => {
if (userUpdated) {
return userMapper.responseMapping(
userConst.CODE.Success,
userConst.MESSAGE.Success
);
} else {
console.log("Failed to update user");
return userMapper.responseMapping(
userConst.CODE.INTRNLSRVR,
userConst.MESSAGE.internalServerError
);
}
});
}
});
}
}
/**for get notificaion preference */
function getNotificationPreference(req) {
let userId = req.params.userId;
if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.InvalidDetails
);
} else {
let userQuery = {
_id: userId,
tb_user_isActive: true,
};
return userDao.getProfile(userQuery).then((userDetails) => {
if (!userDetails) {
return userMapper.responseMapping(
userConst.CODE.DataNotFound,
userConst.MESSAGE.InvalidCredentials
);
} else {
let responseData = {
tb_user_isTradingAlertAllowed:
userDetails.tb_user_isTradingAlertAllowed,
tb_user_isExchangeAlertAllowed:
userDetails.tb_user_isExchangeAlertAllowed,
};
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.Success,
responseData
);
}
});
}
}
/** Check Blacklist token */
function checkBlackListToken(req) {
let blackListMasterDao = new dao(blackListMaster);
return blackListMasterDao.findOne({ token: req.headers.authorization });
}
/**for get trade fund preference */
function getTradeFundPreference(req) {
let userId = req.params.userId;
if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.InvalidDetails
);
} else {
let userQuery = {
_id: userId,
tb_user_isActive: true,
};
return userDao.getProfile(userQuery).then((userDetails) => {
if (!userDetails) {
return userMapper.responseMapping(
userConst.CODE.DataNotFound,
userConst.MESSAGE.InvalidCredentials
);
} else {
let responseData = {
tb_user_fund_trade_preference:
userDetails.tb_user_fund_trade_preference,
};
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.Success,
responseData
);
}
});
}
}
/**for get trade fund preference */
function getTermsAndPolicy(req) {
let userId = req.params.userId;
if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.InvalidDetails
);
} else {
let query = {
type: userConst.CMS_TYPES.termsAndCondition,
status: constants.STATUS.active,
};
return userDao.getCms(query).then((cms) => {
if (!cms) {
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.Success,
{}
);
} else {
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.Success,
cms
);
}
});
}
}
/**for add contact us request*/
function addcontactUs(req) {
let userId = req.params.userId;
if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.InvalidDetails
);
} else {
let query = {
type: userConst.CMS_TYPES.contactUs,
content: req.body.content,
subject: req.body.subject,
createdBy: mongoose.Types.ObjectId(userId),
createdAt: new Date().getTime(),
};
return userDao.addContactUs(query).then((cms) => {
if (!cms) {
console.log("Failed to save contact us");
return userMapper.responseMapping(
userConst.CODE.INTRNLSRVR,
userConst.MESSAGE.internalServerError
);
} else {
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.Success,
cms
);
}
});
}
}
// User Delete
function deleteAccount(req) {
let query = {
_id: req.params.userId,
};
let update = {
tb_user_isDelete: true,
};
return userDao.deleteAccount(query, update).then(async (result) => {
if (result) {
return userMapper.responseMappingWithData(
userConst.CODE.Success,
userConst.MESSAGE.successDeleteUser,
result
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.failedDeleteUser
);
}
});
}
/**for resend verification code */
function resendCode(req) {
let userId = req.params.userId;
if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.InvalidDetails
);
} else {
let userQuery = {
_id: userId,
};
return userDao.getProfile(userQuery).then((userDetails) => {
if (!userDetails) {
return userMapper.responseMapping(
userConst.CODE.DataNotFound,
userConst.MESSAGE.InvalidCredentials
);
} else {
let verificationCode = Math.floor(
Math.random() * (999999 - 100000) + 100000
);
let verificationCodeForSms = Math.floor(
Math.random() * (999999 - 100000) + 100000
);
var mailOptions = {
from: process.env.gmailAccount,
to: userDetails.tb_user_email,
subject: "Email Verification",
html: `<p>Hi,</p><p>Please Verify Your Email.</p><p>Verification Code: <b>${verificationCode}</b>.</p>`,
};
let obj = {
tb_user_verificationCode: verificationCode,
tb_user_verificationCodeTime: Date.now(),
tb_user_verificationCodeForSms: verificationCodeForSms,
};
return userDao
.updateProfile(userQuery, obj)
.then(async (userUpdated) => {
if (userUpdated) {
await appUtils.sendMail(mailOptions);
let message =
userConst.MESSAGE.smsVerifiactionMessage +
verificationCodeForSms;
await appUtils.sendSms({
mobileNumber: userDetails.tb_user_mobile,
message,
});
return userMapper.responseMapping(
userConst.CODE.Success,
userConst.MESSAGE.Success
);
} else {
console.log("Failed to update user");
return userMapper.responseMapping(
userConst.CODE.INTRNLSRVR,
userConst.MESSAGE.internalServerError
);
}
});
}
});
}
}
/**for check reset link validty */
function checkResetLink(req) {
let email = req.params.emailId;
if (!email) {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.InvalidDetails
);
} else {
let userQuery = {
tb_user_email: email,
};
return userDao.getProfile(userQuery).then((userDetails) => {
if (!userDetails) {
return userMapper.responseMapping(
userConst.CODE.DataNotFound,
userConst.MESSAGE.InvalidCredentials
);
} else {
if (userDetails.tb_user_passwordResetTime + 120000 >= Date.now()) {
return userMapper.responseMapping(
userConst.CODE.Success,
userConst.MESSAGE.Success
);
} else {
return userMapper.responseMapping(
userConst.CODE.BadRequest,
userConst.MESSAGE.passwordResetLinkExpired
);
}
}
});
}
}
module.exports = {
loginUser,
signupUserStep1,
signupUserStep2,
signupUserStep3,
forgetPassword,
editProfile,
logoutUser,
resetPassword,
getNotificationsList,
editProfilePicture,
updatePreferences,
getNotificationPreference,
checkBlackListToken,
getTradeFundPreference,
getTermsAndPolicy,
addcontactUs,
deleteAccount,
getProfile,
resendCode,
checkResetLink,
};