@tomei/sso 0.34.2 → 0.34.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -10,201 +10,26 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.LoginUser = void 0;
13
- const general_1 = require("@tomei/general");
13
+ const user_1 = require("./user");
14
+ const redis_service_1 = require("../../redis-client/redis.service");
14
15
  const user_repository_1 = require("./user.repository");
15
- const system_repository_1 = require("../system/system.repository");
16
- const login_history_repository_1 = require("../login-history/login-history.repository");
17
- const password_hash_service_1 = require("../password-hash/password-hash.service");
18
- const user_group_repository_1 = require("../user-group/user-group.repository");
19
16
  const staff_entity_1 = require("../../models/staff.entity");
20
- const system_privilege_entity_1 = require("../../models/system-privilege.entity");
21
- const yn_enum_1 = require("../../enum/yn.enum");
22
- const enum_1 = require("../../enum");
23
- const config_1 = require("@tomei/config");
24
- const sequelize_1 = require("sequelize");
25
- const activity_history_1 = require("@tomei/activity-history");
26
- const user_entity_1 = require("../../models/user.entity");
27
- const group_entity_1 = require("../../models/group.entity");
28
- const group_system_access_repository_1 = require("../group-system-access/group-system-access.repository");
29
- const group_repository_1 = require("../group/group.repository");
30
- const system_entity_1 = require("../../models/system.entity");
31
- const user_system_access_repository_1 = require("../user-system-access/user-system-access.repository");
32
- const group_system_access_entity_1 = require("../../models/group-system-access.entity");
33
- const user_privilege_repository_1 = require("../user-privilege/user-privilege.repository");
34
- const user_object_privilege_repository_1 = require("../user-object-privilege/user-object-privilege.repository");
35
- const group_privilege_entity_1 = require("../../models/group-privilege.entity");
36
- const group_object_privilege_repository_1 = require("../group-object-privilege/group-object-privilege.repository");
37
- const speakeasy = require("speakeasy");
38
- const login_status_enum_1 = require("../../enum/login-status.enum");
39
- const redis_service_1 = require("../../redis-client/redis.service");
40
- class LoginUser extends general_1.LoginUserBase {
41
- get SessionService() {
42
- return this._SessionService;
43
- }
44
- get UserId() {
45
- return parseInt(this.ObjectId);
46
- }
47
- set UserId(value) {
48
- this.ObjectId = value.toString();
49
- }
50
- get Password() {
51
- return this._Password;
52
- }
53
- set Password(value) {
54
- this._Password = value;
55
- }
56
- get Status() {
57
- return this._Status;
58
- }
59
- set Status(value) {
60
- this._Status = value;
61
- }
62
- get UserName() {
63
- return this._UserName;
64
- }
65
- set UserName(value) {
66
- this._UserName = value;
67
- }
68
- get DefaultPasswordChangedYN() {
69
- return this._DefaultPasswordChangedYN;
70
- }
71
- set DefaultPasswordChangedYN(value) {
72
- this._DefaultPasswordChangedYN = value;
73
- }
74
- get FirstLoginAt() {
75
- return this._FirstLoginAt;
76
- }
77
- set FirstLoginAt(value) {
78
- this._FirstLoginAt = value;
79
- }
80
- get LastLoginAt() {
81
- return this._LastLoginAt;
82
- }
83
- set LastLoginAt(value) {
84
- this._LastLoginAt = value;
85
- }
86
- get MFAEnabled() {
87
- return this._MFAEnabled;
88
- }
89
- set MFAEnabled(value) {
90
- this._MFAEnabled = value;
91
- }
92
- get MFAConfig() {
93
- return this._MFAConfig;
94
- }
95
- set MFAConfig(value) {
96
- this._MFAConfig = value;
97
- }
98
- get RecoveryEmail() {
99
- return this._RecoveryEmail;
100
- }
101
- set RecoveryEmail(value) {
102
- this._RecoveryEmail = value;
103
- }
104
- get FailedLoginAttemptCount() {
105
- return this._FailedLoginAttemptCount;
106
- }
107
- set FailedLoginAttemptCount(value) {
108
- this._FailedLoginAttemptCount = value;
109
- }
110
- get LastFailedLoginAt() {
111
- return this._LastFailedLoginAt;
112
- }
113
- set LastFailedLoginAt(value) {
114
- this._LastFailedLoginAt = value;
115
- }
116
- get LastPasswordChangedAt() {
117
- return this._LastPasswordChangedAt;
118
- }
119
- set LastPasswordChangedAt(value) {
120
- this._LastPasswordChangedAt = value;
121
- }
122
- get NeedToChangePasswordYN() {
123
- return this._NeedToChangePasswordYN;
124
- }
125
- set NeedToChangePasswordYN(value) {
126
- this._NeedToChangePasswordYN = value;
127
- }
128
- get CreatedById() {
129
- return this._CreatedById;
130
- }
131
- set CreatedById(value) {
132
- this._CreatedById = value;
133
- }
134
- get CreatedAt() {
135
- return this._CreatedAt;
136
- }
137
- set CreatedAt(value) {
138
- this._CreatedAt = value;
139
- }
140
- get UpdatedById() {
141
- return this._UpdatedById;
142
- }
143
- set UpdatedById(value) {
144
- this._UpdatedById = value;
145
- }
146
- get UpdatedAt() {
147
- return this._UpdatedAt;
148
- }
149
- set UpdatedAt(value) {
150
- this._UpdatedAt = value;
151
- }
152
- getDetails() {
153
- return __awaiter(this, void 0, void 0, function* () {
154
- return {
155
- FullName: this.FullName,
156
- UserName: this.UserName,
157
- IDNo: this.IDNo,
158
- IDType: this.IDType,
159
- Email: this.Email,
160
- ContactNo: this.ContactNo,
161
- };
162
- });
163
- }
164
- constructor(sessionService, dbTransaction, userInfo) {
165
- super();
166
- this.ObjectName = 'User';
167
- this.TableName = 'sso_Users';
168
- this.ObjectType = 'User';
169
- this._SessionService = sessionService;
170
- if (dbTransaction) {
171
- this._dbTransaction = dbTransaction;
172
- }
173
- if (userInfo) {
174
- this.UserId = userInfo.UserId;
175
- this.UserName = userInfo.FullName;
176
- this.FullName = userInfo.FullName;
177
- this.IDNo = userInfo.IDNo;
178
- this.Email = userInfo.Email;
179
- this.ContactNo = userInfo.ContactNo;
180
- this.Password = userInfo.Password;
181
- this.staffs = userInfo.staffs;
182
- this.Status = userInfo.Status;
183
- this.DefaultPasswordChangedYN = userInfo.DefaultPasswordChangedYN;
184
- this.FirstLoginAt = userInfo.FirstLoginAt;
185
- this.LastLoginAt = userInfo.LastLoginAt;
186
- this.MFAEnabled = userInfo.MFAEnabled;
187
- this.MFAConfig = userInfo.MFAConfig;
188
- this.RecoveryEmail = userInfo.RecoveryEmail;
189
- this.FailedLoginAttemptCount = userInfo.FailedLoginAttemptCount;
190
- this.LastFailedLoginAt = userInfo.LastFailedLoginAt;
191
- this.LastPasswordChangedAt = userInfo.LastPasswordChangedAt;
192
- this.NeedToChangePasswordYN = userInfo.NeedToChangePasswordYN;
193
- this.CreatedById = userInfo.CreatedById;
194
- this.CreatedAt = userInfo.CreatedAt;
195
- this.UpdatedById = userInfo.UpdatedById;
196
- this.UpdatedAt = userInfo.UpdatedAt;
197
- }
17
+ class LoginUser extends user_1.User {
18
+ constructor() {
19
+ super(...arguments);
20
+ this.session = {
21
+ Id: null,
22
+ };
198
23
  }
199
24
  static init(sessionService, userId, dbTransaction = null) {
200
25
  var _a, _b, _c;
201
26
  return __awaiter(this, void 0, void 0, function* () {
202
- LoginUser._RedisService = yield redis_service_1.RedisService.init();
27
+ user_1.User._RedisService = yield redis_service_1.RedisService.init();
203
28
  if (userId) {
204
29
  if (dbTransaction) {
205
- LoginUser._Repository = new user_repository_1.UserRepository();
30
+ user_1.User._Repository = new user_repository_1.UserRepository();
206
31
  }
207
- const user = yield LoginUser._Repository.findOne({
32
+ const user = yield user_1.User._Repository.findOne({
208
33
  where: {
209
34
  UserId: userId,
210
35
  },
@@ -253,453 +78,6 @@ class LoginUser extends general_1.LoginUserBase {
253
78
  return new LoginUser(sessionService, dbTransaction);
254
79
  });
255
80
  }
256
- setEmail(email, dbTransaction) {
257
- return __awaiter(this, void 0, void 0, function* () {
258
- try {
259
- if (this.Email === email) {
260
- return;
261
- }
262
- const user = yield LoginUser._Repository.findOne({
263
- where: {
264
- Email: email,
265
- },
266
- transaction: dbTransaction,
267
- });
268
- if (user) {
269
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Email already exists');
270
- }
271
- this.Email = email;
272
- }
273
- catch (error) {
274
- throw error;
275
- }
276
- });
277
- }
278
- login(systemCode, email, password, ipAddress, dbTransaction) {
279
- var _a, _b, _c;
280
- return __awaiter(this, void 0, void 0, function* () {
281
- try {
282
- if (!this.ObjectId) {
283
- const user = yield LoginUser._Repository.findOne({
284
- transaction: dbTransaction,
285
- where: {
286
- Email: email,
287
- Status: {
288
- [sequelize_1.Op.or]: [enum_1.UserStatus.ACTIVE, enum_1.UserStatus.LOCKED],
289
- },
290
- },
291
- include: [
292
- {
293
- model: staff_entity_1.default,
294
- },
295
- ],
296
- });
297
- if (user) {
298
- const userAttr = {
299
- UserId: user.UserId,
300
- UserName: user.UserName,
301
- FullName: ((_a = user === null || user === void 0 ? void 0 : user.Staff) === null || _a === void 0 ? void 0 : _a.FullName) || null,
302
- IDNo: ((_b = user === null || user === void 0 ? void 0 : user.Staff) === null || _b === void 0 ? void 0 : _b.IdNo) || null,
303
- ContactNo: ((_c = user === null || user === void 0 ? void 0 : user.Staff) === null || _c === void 0 ? void 0 : _c.Mobile) || null,
304
- Email: user.Email,
305
- Password: user.Password,
306
- Status: user.Status,
307
- DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
308
- FirstLoginAt: user.FirstLoginAt,
309
- LastLoginAt: user.LastLoginAt,
310
- MFAEnabled: user.MFAEnabled,
311
- MFAConfig: user.MFAConfig,
312
- RecoveryEmail: user.RecoveryEmail,
313
- FailedLoginAttemptCount: user.FailedLoginAttemptCount,
314
- LastFailedLoginAt: user.LastFailedLoginAt,
315
- LastPasswordChangedAt: user.LastPasswordChangedAt,
316
- NeedToChangePasswordYN: user.NeedToChangePasswordYN,
317
- CreatedById: user.CreatedById,
318
- CreatedAt: user.CreatedAt,
319
- UpdatedById: user.UpdatedById,
320
- UpdatedAt: user.UpdatedAt,
321
- staffs: (user === null || user === void 0 ? void 0 : user.Staff) || null,
322
- };
323
- this.UserId = userAttr.UserId;
324
- this.FullName = userAttr.FullName;
325
- this.IDNo = userAttr.IDNo;
326
- this.Email = userAttr.Email;
327
- this.ContactNo = userAttr.ContactNo;
328
- this.Password = userAttr.Password;
329
- this.Status = userAttr.Status;
330
- this.DefaultPasswordChangedYN = userAttr.DefaultPasswordChangedYN;
331
- this.FirstLoginAt = userAttr.FirstLoginAt;
332
- this.LastLoginAt = userAttr.LastLoginAt;
333
- this.MFAEnabled = userAttr.MFAEnabled;
334
- this.MFAConfig = userAttr.MFAConfig;
335
- this.RecoveryEmail = userAttr.RecoveryEmail;
336
- this.FailedLoginAttemptCount = userAttr.FailedLoginAttemptCount;
337
- this.LastFailedLoginAt = userAttr.LastFailedLoginAt;
338
- this.LastPasswordChangedAt = userAttr.LastPasswordChangedAt;
339
- this.NeedToChangePasswordYN = userAttr.NeedToChangePasswordYN;
340
- this.CreatedById = userAttr.CreatedById;
341
- this.CreatedAt = userAttr.CreatedAt;
342
- this.UpdatedById = userAttr.UpdatedById;
343
- this.UpdatedAt = userAttr.UpdatedAt;
344
- this.staffs = userAttr.staffs;
345
- }
346
- else {
347
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
348
- }
349
- }
350
- if (this.ObjectId && this.Email !== email) {
351
- throw new Error('Invalid credentials.');
352
- }
353
- const check2FA = yield LoginUser.check2FA(this, dbTransaction);
354
- try {
355
- const system = yield LoginUser._SystemRepository.findOne({
356
- where: {
357
- SystemCode: systemCode,
358
- Status: 'Active',
359
- },
360
- });
361
- if (!system) {
362
- throw new Error('Invalid credentials.');
363
- }
364
- const passwordHashService = new password_hash_service_1.PasswordHashService();
365
- const isPasswordValid = yield passwordHashService.verify(password, this.Password);
366
- if (!isPasswordValid) {
367
- throw new Error('Invalid credentials.');
368
- }
369
- yield this.checkSystemAccess(this.UserId, system.SystemCode, dbTransaction);
370
- if (this.Status === enum_1.UserStatus.LOCKED) {
371
- const isReleaseLock = LoginUser.shouldReleaseLock(this.LastFailedLoginAt);
372
- if (isReleaseLock) {
373
- yield LoginUser.releaseLock(this.UserId, dbTransaction);
374
- this.Status = enum_1.UserStatus.ACTIVE;
375
- }
376
- else {
377
- throw new Error('Invalid credentials.');
378
- }
379
- }
380
- }
381
- catch (error) {
382
- yield this.incrementFailedLoginAttemptCount(dbTransaction);
383
- }
384
- const system = yield LoginUser._SystemRepository.findOne({
385
- where: {
386
- SystemCode: systemCode,
387
- },
388
- });
389
- yield this.alertNewLogin(this.ObjectId, system.SystemCode, ipAddress);
390
- this.FailedLoginAttemptCount = 0;
391
- this.LastLoginAt = new Date();
392
- if (!this.FirstLoginAt) {
393
- this.FirstLoginAt = new Date();
394
- }
395
- yield LoginUser._Repository.update({
396
- FullName: this.FullName,
397
- UserName: this.UserName,
398
- IDNo: this.IDNo,
399
- Email: this.Email,
400
- ContactNo: this.ContactNo,
401
- Password: this.Password,
402
- Status: this.Status,
403
- DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
404
- FirstLoginAt: this.FirstLoginAt,
405
- LastLoginAt: this.LastLoginAt,
406
- MFAEnabled: this.MFAEnabled,
407
- MFAConfig: this.MFAConfig,
408
- RecoveryEmail: this.RecoveryEmail,
409
- FailedLoginAttemptCount: this.FailedLoginAttemptCount,
410
- LastFailedLoginAt: this.LastFailedLoginAt,
411
- LastPasswordChangedAt: this.LastPasswordChangedAt,
412
- NeedToChangePasswordYN: this.NeedToChangePasswordYN,
413
- }, {
414
- where: {
415
- UserId: this.UserId,
416
- },
417
- transaction: dbTransaction,
418
- });
419
- const userSession = yield this._SessionService.retrieveUserSession(this.ObjectId);
420
- let systemLogin = userSession.systemLogins.find((system) => system.code === systemCode);
421
- const { randomUUID } = require('crypto');
422
- const sessionId = randomUUID();
423
- if (systemLogin) {
424
- systemLogin = systemLogin.sessionId = sessionId;
425
- userSession.systemLogins.map((system) => system.code === systemCode ? systemLogin : system);
426
- }
427
- else {
428
- const newLogin = {
429
- id: system.SystemCode,
430
- code: system.SystemCode,
431
- sessionId: sessionId,
432
- privileges: yield this.getPrivileges(system.SystemCode, dbTransaction),
433
- };
434
- userSession.systemLogins.push(newLogin);
435
- }
436
- this._SessionService.setUserSession(this.ObjectId, userSession);
437
- yield LoginUser._LoginHistoryRepository.create({
438
- UserId: this.UserId,
439
- SystemCode: system.SystemCode,
440
- OriginIp: ipAddress,
441
- CreatedAt: new Date(),
442
- LoginStatus: login_status_enum_1.LoginStatusEnum.SUCCESS,
443
- }, {
444
- transaction: dbTransaction,
445
- });
446
- const is2FAEnabledYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'is2FAEnabledYN');
447
- if (is2FAEnabledYN === 'Y') {
448
- return `${this.UserId}:`;
449
- }
450
- return `${this.UserId}:${sessionId}`;
451
- }
452
- catch (error) {
453
- if (this.ObjectId) {
454
- yield LoginUser._LoginHistoryRepository.create({
455
- UserId: this.UserId,
456
- SystemCode: systemCode,
457
- OriginIp: ipAddress,
458
- LoginStatus: login_status_enum_1.LoginStatusEnum.FAILURE,
459
- CreatedAt: new Date(),
460
- }, {
461
- transaction: dbTransaction,
462
- });
463
- }
464
- throw error;
465
- }
466
- });
467
- }
468
- checkSystemAccess(userId, systemCode, dbTransaction) {
469
- return __awaiter(this, void 0, void 0, function* () {
470
- try {
471
- let isUserHaveAccess = false;
472
- const systemAccess = yield LoginUser._UserSystemAccessRepo.findOne({
473
- where: {
474
- UserId: userId,
475
- SystemCode: systemCode,
476
- Status: 'Active',
477
- },
478
- dbTransaction,
479
- });
480
- if (systemAccess) {
481
- isUserHaveAccess = true;
482
- }
483
- else {
484
- const userGroups = yield LoginUser._UserGroupRepo.findAll({
485
- where: {
486
- UserId: userId,
487
- InheritGroupAccessYN: 'Y',
488
- Status: 'Active',
489
- },
490
- include: [
491
- {
492
- model: group_entity_1.default,
493
- },
494
- ],
495
- dbTransaction,
496
- });
497
- for (const usergroup of userGroups) {
498
- const group = usergroup.Group;
499
- const groupSystemAccess = yield LoginUser.getInheritedSystemAccess(dbTransaction, group);
500
- for (const system of groupSystemAccess) {
501
- if (system.SystemCode === systemCode) {
502
- isUserHaveAccess = true;
503
- break;
504
- }
505
- }
506
- }
507
- }
508
- if (!isUserHaveAccess) {
509
- throw new Error("User don't have access to the system.");
510
- }
511
- }
512
- catch (error) {
513
- throw error;
514
- }
515
- });
516
- }
517
- alertNewLogin(userId, systemCode, ipAddress) {
518
- return __awaiter(this, void 0, void 0, function* () {
519
- try {
520
- const userLogins = yield LoginUser._LoginHistoryRepository.findAll({
521
- where: {
522
- UserId: userId,
523
- SystemCode: systemCode,
524
- },
525
- });
526
- const gotPreviousLogins = (userLogins === null || userLogins === void 0 ? void 0 : userLogins.length) !== 0;
527
- let ipFound = undefined;
528
- if (gotPreviousLogins) {
529
- ipFound = userLogins.find((item) => item.OriginIp === ipAddress);
530
- }
531
- }
532
- catch (error) {
533
- throw error;
534
- }
535
- });
536
- }
537
- getPrivileges(systemCode, dbTransaction) {
538
- return __awaiter(this, void 0, void 0, function* () {
539
- try {
540
- const system = yield LoginUser._SystemRepository.findOne({
541
- where: {
542
- SystemCode: systemCode,
543
- },
544
- transaction: dbTransaction,
545
- });
546
- if (!system) {
547
- throw new Error('Invalid system code.');
548
- }
549
- const userPrivileges = yield this.getUserPersonalPrivileges(systemCode, dbTransaction);
550
- const objectPrivileges = yield this.getObjectPrivileges(systemCode, dbTransaction);
551
- const userGroupOwnByUser = yield LoginUser._UserGroupRepo.findAll({
552
- where: {
553
- UserId: this.UserId,
554
- InheritGroupSystemAccessYN: 'Y',
555
- InheritGroupPrivilegeYN: 'Y',
556
- Status: 'Active',
557
- },
558
- include: [
559
- {
560
- model: group_entity_1.default,
561
- where: {
562
- Status: 'Active',
563
- },
564
- include: [
565
- {
566
- model: group_system_access_entity_1.default,
567
- where: {
568
- SystemCode: systemCode,
569
- },
570
- },
571
- ],
572
- },
573
- ],
574
- transaction: dbTransaction,
575
- });
576
- let groupsPrivileges = [];
577
- for (const userGroup of userGroupOwnByUser) {
578
- const gp = yield this.getInheritedPrivileges(userGroup.GroupCode, systemCode, dbTransaction);
579
- groupsPrivileges = [...groupsPrivileges, ...gp];
580
- }
581
- const privileges = [
582
- ...userPrivileges,
583
- ...objectPrivileges,
584
- ...groupsPrivileges,
585
- ];
586
- return privileges;
587
- }
588
- catch (error) {
589
- throw error;
590
- }
591
- });
592
- }
593
- getInheritedPrivileges(groupCode, systemCode, dbTransaction) {
594
- return __awaiter(this, void 0, void 0, function* () {
595
- try {
596
- const group = yield LoginUser._GroupRepo.findOne({
597
- where: {
598
- GroupCode: groupCode,
599
- Status: 'Active',
600
- },
601
- include: [
602
- {
603
- model: group_privilege_entity_1.default,
604
- where: {
605
- Status: 'Active',
606
- },
607
- include: [
608
- {
609
- model: system_privilege_entity_1.default,
610
- where: {
611
- SystemCode: systemCode,
612
- Status: 'Active',
613
- },
614
- },
615
- ],
616
- },
617
- ],
618
- transaction: dbTransaction,
619
- });
620
- const objectPrivileges = yield LoginUser._GroupObjectPrivilegeRepo.findAll({
621
- where: {
622
- GroupCode: groupCode,
623
- },
624
- include: {
625
- model: system_privilege_entity_1.default,
626
- where: {
627
- SystemCode: systemCode,
628
- Status: 'Active',
629
- },
630
- },
631
- transaction: dbTransaction,
632
- });
633
- let privileges = [];
634
- const groupPrivileges = [];
635
- for (const groupPrivilege of group.GroupPrivileges) {
636
- groupPrivileges.push(groupPrivilege.Privilege.PrivilegeCode);
637
- }
638
- const ops = [];
639
- for (const objectPrivilege of objectPrivileges) {
640
- ops.push(objectPrivilege.Privilege.PrivilegeCode);
641
- }
642
- privileges = [...privileges, ...groupPrivileges, ...ops];
643
- if (group.ParentGroupCode && group.InheritParentPrivilegeYN === 'Y') {
644
- const parentGroupPrivileges = yield this.getInheritedPrivileges(group.ParentGroupCode, systemCode, dbTransaction);
645
- privileges = [...privileges, ...parentGroupPrivileges];
646
- }
647
- return privileges;
648
- }
649
- catch (error) {
650
- throw error;
651
- }
652
- });
653
- }
654
- getUserPersonalPrivileges(systemCode, dbTransaction) {
655
- return __awaiter(this, void 0, void 0, function* () {
656
- try {
657
- const userPrivileges = yield LoginUser._UserPrivilegeRepo.findAll({
658
- where: {
659
- UserId: this.UserId,
660
- Status: 'Active',
661
- },
662
- include: {
663
- model: system_privilege_entity_1.default,
664
- where: {
665
- SystemCode: systemCode,
666
- Status: 'Active',
667
- },
668
- },
669
- transaction: dbTransaction,
670
- });
671
- const privileges = userPrivileges.map((u) => u.Privilege.PrivilegeCode);
672
- return privileges;
673
- }
674
- catch (error) {
675
- throw error;
676
- }
677
- });
678
- }
679
- getObjectPrivileges(systemCode, dbTransaction) {
680
- return __awaiter(this, void 0, void 0, function* () {
681
- try {
682
- const userObjectPrivileges = yield LoginUser._UserObjectPrivilegeRepo.findAll({
683
- where: {
684
- UserId: this.UserId,
685
- },
686
- include: {
687
- model: system_privilege_entity_1.default,
688
- where: {
689
- SystemCode: systemCode,
690
- Status: 'Active',
691
- },
692
- },
693
- transaction: dbTransaction,
694
- });
695
- const privilegesCodes = userObjectPrivileges.map((u) => u.Privilege.PrivilegeCode);
696
- return privilegesCodes;
697
- }
698
- catch (error) {
699
- throw error;
700
- }
701
- });
702
- }
703
81
  checkPrivileges(systemCode, privilegeName) {
704
82
  return __awaiter(this, void 0, void 0, function* () {
705
83
  try {
@@ -758,850 +136,6 @@ class LoginUser extends general_1.LoginUserBase {
758
136
  }
759
137
  });
760
138
  }
761
- static checkUserInfoDuplicated(dbTransaction, query) {
762
- return __awaiter(this, void 0, void 0, function* () {
763
- try {
764
- const { Email, UserName, IdType, IdNo, ContactNo } = query;
765
- const where = {
766
- [sequelize_1.Op.or]: {},
767
- };
768
- if (Email) {
769
- where[sequelize_1.Op.or]['Email'] = Email;
770
- }
771
- if (UserName) {
772
- where[sequelize_1.Op.or]['UserName'] = UserName;
773
- }
774
- if (IdType && IdNo) {
775
- where[sequelize_1.Op.or]['IdType'] = IdType;
776
- where[sequelize_1.Op.or]['IdNo'] = IdNo;
777
- }
778
- if (ContactNo) {
779
- where[sequelize_1.Op.or]['ContactNo'] = ContactNo;
780
- }
781
- const user = yield LoginUser._Repository.findAll({
782
- where,
783
- transaction: dbTransaction,
784
- });
785
- if (user && user.length > 0) {
786
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'User info already exists');
787
- }
788
- }
789
- catch (error) {
790
- throw error;
791
- }
792
- });
793
- }
794
- static generateDefaultPassword() {
795
- try {
796
- const passwordPolicy = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'passwordPolicy');
797
- if (!passwordPolicy ||
798
- !passwordPolicy.maxLen ||
799
- !passwordPolicy.minLen ||
800
- !passwordPolicy.nonAcceptableChar ||
801
- !passwordPolicy.numOfCapitalLetters ||
802
- !passwordPolicy.numOfNumbers ||
803
- !passwordPolicy.numOfSpecialChars) {
804
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing password policy. Please set in config file.');
805
- }
806
- if (passwordPolicy.numOfCapitalLetters +
807
- passwordPolicy.numOfNumbers +
808
- passwordPolicy.numOfSpecialChars >
809
- passwordPolicy.maxLen) {
810
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Password policy is invalid. Please set in config file.');
811
- }
812
- const { maxLen, minLen, nonAcceptableChar, numOfCapitalLetters, numOfNumbers, numOfSpecialChars, } = passwordPolicy;
813
- const passwordLength = Math.floor(Math.random() * (maxLen - minLen + 1)) + minLen;
814
- const words = 'abcdefghijklmnopqrstuvwxyz';
815
- const capitalLetters = words.toUpperCase();
816
- const numbers = '0123456789';
817
- const specialChars = '!@#$%^&*()_+-={}[]|:;"<>,.?/~`';
818
- const nonAcceptableChars = nonAcceptableChar.split(',');
819
- const filteredWords = words
820
- .split('')
821
- .filter((word) => !nonAcceptableChars.includes(word));
822
- const filteredCapitalLetters = capitalLetters
823
- .split('')
824
- .filter((word) => !nonAcceptableChars.includes(word));
825
- const filteredNumbers = numbers
826
- .split('')
827
- .filter((word) => !nonAcceptableChars.includes(word));
828
- const filteredSpecialChars = specialChars
829
- .split('')
830
- .filter((word) => !nonAcceptableChars.includes(word));
831
- const generatedCapitalLetters = [];
832
- const generatedNumbers = [];
833
- const generatedSpecialChars = [];
834
- const generatedWords = [];
835
- for (let i = 0; i < numOfCapitalLetters; i++) {
836
- const randomIndex = Math.floor(Math.random() * filteredCapitalLetters.length);
837
- generatedCapitalLetters.push(filteredCapitalLetters[randomIndex]);
838
- }
839
- for (let i = 0; i < numOfNumbers; i++) {
840
- const randomIndex = Math.floor(Math.random() * filteredNumbers.length);
841
- generatedNumbers.push(filteredNumbers[randomIndex]);
842
- }
843
- for (let i = 0; i < numOfSpecialChars; i++) {
844
- const randomIndex = Math.floor(Math.random() * filteredSpecialChars.length);
845
- generatedSpecialChars.push(filteredSpecialChars[randomIndex]);
846
- }
847
- for (let i = 0; i <
848
- passwordLength -
849
- (numOfCapitalLetters + numOfNumbers + numOfSpecialChars); i++) {
850
- const randomIndex = Math.floor(Math.random() * filteredWords.length);
851
- generatedWords.push(filteredWords[randomIndex]);
852
- }
853
- let generatedPassword = '';
854
- const allGeneratedChars = generatedCapitalLetters.concat(generatedNumbers, generatedSpecialChars, generatedWords);
855
- allGeneratedChars.sort(() => Math.random() - 0.5);
856
- generatedPassword = allGeneratedChars.join('');
857
- return generatedPassword;
858
- }
859
- catch (error) {
860
- throw error;
861
- }
862
- }
863
- static setPassword(dbTransaction, user, password) {
864
- return __awaiter(this, void 0, void 0, function* () {
865
- try {
866
- const passwordPolicy = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'passwordPolicy');
867
- if (!passwordPolicy ||
868
- !passwordPolicy.maxLen ||
869
- !passwordPolicy.minLen ||
870
- !passwordPolicy.nonAcceptableChar ||
871
- !passwordPolicy.numOfCapitalLetters ||
872
- !passwordPolicy.numOfNumbers ||
873
- !passwordPolicy.numOfSpecialChars) {
874
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing password policy. Please set in config file.');
875
- }
876
- try {
877
- if (password.length < passwordPolicy.minLen) {
878
- throw Error('Password is too short');
879
- }
880
- if (password.length > passwordPolicy.maxLen) {
881
- throw Error('Password is too long');
882
- }
883
- const nonAcceptableChars = passwordPolicy.nonAcceptableChar.split(',');
884
- const nonAcceptableCharsFound = nonAcceptableChars.some((char) => password.includes(char));
885
- if (nonAcceptableCharsFound) {
886
- throw Error('Password contains unacceptable characters');
887
- }
888
- const capitalLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
889
- const numOfCapitalLetters = passwordPolicy.numOfCapitalLetters;
890
- const capitalLettersFound = capitalLetters
891
- .split('')
892
- .filter((char) => password.includes(char)).length;
893
- if (capitalLettersFound < numOfCapitalLetters) {
894
- throw Error('Password does not contain enough capital letters');
895
- }
896
- const numbers = '0123456789';
897
- const numOfNumbers = passwordPolicy.numOfNumbers;
898
- const numbersFound = numbers
899
- .split('')
900
- .filter((char) => password.includes(char)).length;
901
- if (numbersFound < numOfNumbers) {
902
- throw Error('Password does not contain enough numbers');
903
- }
904
- const specialChars = '!@#$%^&*()_+-={}[]|:;"<>,.?/~`';
905
- const numOfSpecialChars = passwordPolicy.numOfSpecialChars;
906
- const specialCharsFound = specialChars
907
- .split('')
908
- .filter((char) => password.includes(char)).length;
909
- if (specialCharsFound < numOfSpecialChars) {
910
- throw Error('Password does not contain enough special characters');
911
- }
912
- }
913
- catch (error) {
914
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', "Your password doesn't meet security requirements. Try using a mix of uppercase and lowercase letters, numbers, and symbols.");
915
- }
916
- const passwordHashService = new password_hash_service_1.PasswordHashService();
917
- const hashedPassword = yield passwordHashService.hashPassword(password);
918
- user._Password = hashedPassword;
919
- return user;
920
- }
921
- catch (error) {
922
- throw error;
923
- }
924
- });
925
- }
926
- static create(loginUser, dbTransaction, user) {
927
- return __awaiter(this, void 0, void 0, function* () {
928
- try {
929
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
930
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'User - Create');
931
- if (!isPrivileged) {
932
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to create user');
933
- }
934
- if (!user.Email && !user.UserName) {
935
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Email and Username is required');
936
- }
937
- yield LoginUser.checkUserInfoDuplicated(dbTransaction, {
938
- Email: user.Email,
939
- UserName: user.UserName,
940
- IdType: user.IDType,
941
- IdNo: user.IDNo,
942
- ContactNo: user.ContactNo,
943
- });
944
- const defaultPassword = LoginUser.generateDefaultPassword();
945
- user = yield LoginUser.setPassword(dbTransaction, user, defaultPassword);
946
- const userInfo = {
947
- UserName: user.UserName,
948
- FullName: user.FullName,
949
- IDNo: user.IDNo,
950
- Email: user.Email,
951
- ContactNo: user.ContactNo,
952
- Password: user.Password,
953
- Status: enum_1.UserStatus.ACTIVE,
954
- FirstLoginAt: null,
955
- LastLoginAt: null,
956
- MFAEnabled: null,
957
- MFAConfig: null,
958
- RecoveryEmail: null,
959
- FailedLoginAttemptCount: 0,
960
- LastFailedLoginAt: null,
961
- LastPasswordChangedAt: null,
962
- DefaultPasswordChangedYN: yn_enum_1.YN.No,
963
- NeedToChangePasswordYN: yn_enum_1.YN.Yes,
964
- CreatedById: loginUser.UserId,
965
- CreatedAt: new Date(),
966
- UpdatedById: loginUser.UserId,
967
- UpdatedAt: new Date(),
968
- UserId: null,
969
- };
970
- const newUser = yield LoginUser._Repository.create({
971
- Email: userInfo.Email,
972
- UserName: userInfo.UserName,
973
- Password: userInfo.Password,
974
- Status: userInfo.Status,
975
- DefaultPasswordChangedYN: userInfo.DefaultPasswordChangedYN,
976
- FirstLoginAt: userInfo.FirstLoginAt,
977
- LastLoginAt: userInfo.LastLoginAt,
978
- MFAEnabled: userInfo.MFAEnabled,
979
- MFAConfig: userInfo.MFAConfig,
980
- RecoveryEmail: userInfo.RecoveryEmail,
981
- FailedLoginAttemptCount: userInfo.FailedLoginAttemptCount,
982
- LastFailedLoginAt: userInfo.LastFailedLoginAt,
983
- LastPasswordChangedAt: userInfo.LastPasswordChangedAt,
984
- NeedToChangePasswordYN: userInfo.NeedToChangePasswordYN,
985
- CreatedById: userInfo.CreatedById,
986
- CreatedAt: userInfo.CreatedAt,
987
- UpdatedById: userInfo.UpdatedById,
988
- UpdatedAt: userInfo.UpdatedAt,
989
- }, {
990
- transaction: dbTransaction,
991
- });
992
- userInfo.UserId = newUser.UserId;
993
- const userToBeCreated = new LoginUser(loginUser.SessionService, dbTransaction, userInfo);
994
- const activity = new activity_history_1.Activity();
995
- activity.ActivityId = activity.createId();
996
- activity.Action = activity_history_1.ActionEnum.ADD;
997
- activity.Description = 'Create User';
998
- activity.EntityType = 'LoginUser';
999
- activity.EntityId = newUser.UserId.toString();
1000
- activity.EntityValueBefore = JSON.stringify({});
1001
- activity.EntityValueAfter = JSON.stringify(newUser.get({ plain: true }));
1002
- yield activity.create(loginUser.ObjectId, dbTransaction);
1003
- return userToBeCreated;
1004
- }
1005
- catch (error) {
1006
- throw error;
1007
- }
1008
- });
1009
- }
1010
- incrementFailedLoginAttemptCount(dbTransaction) {
1011
- return __awaiter(this, void 0, void 0, function* () {
1012
- const maxFailedLoginAttempts = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'maxFailedLoginAttempts');
1013
- const autoReleaseYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'autoReleaseYN');
1014
- if (!maxFailedLoginAttempts || !autoReleaseYN) {
1015
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing maxFailedLoginAttempts and or autoReleaseYN. Please set in config file.');
1016
- }
1017
- const FailedLoginAttemptCount = this.FailedLoginAttemptCount + 1;
1018
- const LastFailedLoginAt = new Date();
1019
- if (FailedLoginAttemptCount > maxFailedLoginAttempts) {
1020
- this.Status = enum_1.UserStatus.LOCKED;
1021
- }
1022
- yield LoginUser._Repository.update({
1023
- FailedLoginAttemptCount: FailedLoginAttemptCount,
1024
- LastFailedLoginAt: LastFailedLoginAt,
1025
- Status: this.Status,
1026
- }, {
1027
- where: {
1028
- UserId: this.UserId,
1029
- },
1030
- transaction: dbTransaction,
1031
- });
1032
- if (this.Status === enum_1.UserStatus.LOCKED && autoReleaseYN === 'Y') {
1033
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Your account has been temporarily locked due to too many failed login attempts, please try again later.');
1034
- }
1035
- if (this.Status === enum_1.UserStatus.LOCKED && autoReleaseYN === 'N') {
1036
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Your account has been locked due to too many failed login attempts, please contact IT Support for instructions on how to unlock your account');
1037
- }
1038
- if (this.Status == enum_1.UserStatus.LOCKED) {
1039
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid credentials.');
1040
- }
1041
- });
1042
- }
1043
- static shouldReleaseLock(LastFailedLoginAt) {
1044
- const minuteToAutoRelease = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'minuteToAutoRelease');
1045
- const autoReleaseYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'autoReleaseYN');
1046
- if (!minuteToAutoRelease || !autoReleaseYN) {
1047
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing minuteToAutoRelease and or autoReleaseYN. Please set in config file.');
1048
- }
1049
- if (autoReleaseYN === 'Y') {
1050
- const lastFailedDate = new Date(LastFailedLoginAt);
1051
- const currentDate = new Date();
1052
- const timeDifferenceInMillis = currentDate.getTime() - lastFailedDate.getTime();
1053
- const timeDifferenceInMinutes = timeDifferenceInMillis / (1000 * 60);
1054
- if (timeDifferenceInMinutes > +minuteToAutoRelease) {
1055
- return true;
1056
- }
1057
- else {
1058
- return false;
1059
- }
1060
- }
1061
- else if (autoReleaseYN === 'N') {
1062
- return false;
1063
- }
1064
- }
1065
- static releaseLock(UserId, dbTransaction) {
1066
- this._Repository.update({
1067
- FailedLoginAttemptCount: 0,
1068
- Status: enum_1.UserStatus.ACTIVE,
1069
- }, {
1070
- where: {
1071
- UserId: UserId,
1072
- },
1073
- transaction: dbTransaction,
1074
- });
1075
- }
1076
- static getGroups(loginUser, dbTransaction) {
1077
- return __awaiter(this, void 0, void 0, function* () {
1078
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1079
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'UserGroup - List Own');
1080
- if (!isPrivileged) {
1081
- throw new Error('You do not have permission to list UserGroup.');
1082
- }
1083
- const userGroups = yield LoginUser._UserGroupRepo.findAll({
1084
- where: {
1085
- UserId: loginUser.ObjectId,
1086
- Status: 'Active',
1087
- },
1088
- include: [{ model: user_entity_1.default, as: 'User' }, { model: group_entity_1.default }],
1089
- transaction: dbTransaction,
1090
- });
1091
- return userGroups;
1092
- });
1093
- }
1094
- static getInheritedSystemAccess(dbTransaction, group) {
1095
- return __awaiter(this, void 0, void 0, function* () {
1096
- const dataSystemAccesses = yield LoginUser._GroupSystemAccessRepo.findAll({
1097
- where: {
1098
- GroupCode: group.GroupCode,
1099
- Status: 'Active',
1100
- },
1101
- include: [{ model: system_entity_1.default }],
1102
- transaction: dbTransaction,
1103
- });
1104
- let systemAccesses = dataSystemAccesses;
1105
- if (group.InheritParentPrivilegeYN === 'Y' && group.ParentGroupCode) {
1106
- const GroupCode = group.ParentGroupCode;
1107
- const parentGroup = yield LoginUser._GroupRepo.findByPk(GroupCode, dbTransaction);
1108
- const dataParentSystemAccesses = yield LoginUser.getInheritedSystemAccess(dbTransaction, parentGroup);
1109
- const parentSystemAccesses = dataParentSystemAccesses;
1110
- systemAccesses = systemAccesses.concat(parentSystemAccesses);
1111
- }
1112
- return systemAccesses;
1113
- });
1114
- }
1115
- static combineSystemAccess(loginUser, dbTransaction, groups) {
1116
- return __awaiter(this, void 0, void 0, function* () {
1117
- const userAccess = yield LoginUser._UserSystemAccessRepo.findAll({
1118
- where: {
1119
- UserId: loginUser.ObjectId,
1120
- Status: 'Active',
1121
- },
1122
- include: [{ model: system_entity_1.default }],
1123
- transaction: dbTransaction,
1124
- });
1125
- const groupAccessPromises = groups.map((e) => __awaiter(this, void 0, void 0, function* () {
1126
- if (e.InheritParentSystemAccessYN) {
1127
- return yield this.getInheritedSystemAccess(dbTransaction, e);
1128
- }
1129
- else {
1130
- return [];
1131
- }
1132
- }));
1133
- const groupAccess = (yield Promise.all(groupAccessPromises)).flat();
1134
- const allAccess = userAccess.concat(groupAccess);
1135
- const uniqueAccess = new Set(allAccess.filter((value, index, self) => {
1136
- return self.some((prev) => prev.SystemCode === value.SystemCode);
1137
- }));
1138
- return Array.from(uniqueAccess);
1139
- });
1140
- }
1141
- static getSystems(loginUser, dbTransaction) {
1142
- return __awaiter(this, void 0, void 0, function* () {
1143
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1144
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'System – List Own');
1145
- if (!isPrivileged) {
1146
- throw new Error('You do not have permission to list UserGroup.');
1147
- }
1148
- const groups = yield LoginUser.getGroups(loginUser, dbTransaction);
1149
- const systemAccess = yield LoginUser.combineSystemAccess(loginUser, dbTransaction, groups);
1150
- const output = [];
1151
- if (systemAccess) {
1152
- for (let i = 0; i < systemAccess.length; i++) {
1153
- const system = yield LoginUser._SystemRepository.findOne({
1154
- where: {
1155
- SystemCode: systemAccess[i].SystemCode,
1156
- Status: 'Active',
1157
- },
1158
- });
1159
- output.push({
1160
- UserSystemAccessId: systemAccess[i].UserSystemAccessId,
1161
- UserId: systemAccess[i].UserId,
1162
- SystemCode: systemAccess[i].SystemCode,
1163
- Status: systemAccess[i].Status,
1164
- CreatedById: systemAccess[i].CreatedById,
1165
- UpdatedById: systemAccess[i].UpdatedById,
1166
- CreatedAt: systemAccess[i].CreatedAt,
1167
- UpdatedAt: systemAccess[i].UpdatedAt,
1168
- System: system,
1169
- });
1170
- }
1171
- }
1172
- return output;
1173
- });
1174
- }
1175
- static check2FA(loginUser, dbTransaction) {
1176
- return __awaiter(this, void 0, void 0, function* () {
1177
- try {
1178
- const user = yield LoginUser._Repository.findOne({
1179
- where: {
1180
- UserId: loginUser.UserId,
1181
- },
1182
- transaction: dbTransaction,
1183
- });
1184
- if (user.MFAEnabled === 1) {
1185
- return true;
1186
- }
1187
- return false;
1188
- }
1189
- catch (error) {
1190
- throw error;
1191
- }
1192
- });
1193
- }
1194
- static setup2FA(userId, dbTransaction) {
1195
- var _a, _b, _c, _d;
1196
- return __awaiter(this, void 0, void 0, function* () {
1197
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1198
- const user = yield LoginUser._Repository.findOne({
1199
- where: {
1200
- UserId: userId,
1201
- },
1202
- });
1203
- if (!user) {
1204
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1205
- }
1206
- const secretCode = speakeasy.generateSecret({ name: systemCode });
1207
- let userMFAConfig = null;
1208
- if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1209
- try {
1210
- userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1211
- }
1212
- catch (error) {
1213
- console.error('Invalid JSON string on MFAConfig:', error);
1214
- }
1215
- }
1216
- const MFAConfig = {
1217
- totp: {
1218
- enabled: true,
1219
- secret: secretCode.base32,
1220
- issuer: systemCode,
1221
- },
1222
- sms: {
1223
- enabled: ((_a = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.sms) === null || _a === void 0 ? void 0 : _a.enable) || false,
1224
- phoneNumber: ((_b = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.sms) === null || _b === void 0 ? void 0 : _b.phoneNumber) || '',
1225
- },
1226
- email: {
1227
- enabled: ((_c = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.email) === null || _c === void 0 ? void 0 : _c.enable) || false,
1228
- emailAddress: ((_d = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.email) === null || _d === void 0 ? void 0 : _d.emailAddress) || '',
1229
- },
1230
- };
1231
- user.MFAEnabled = 0;
1232
- user.MFAConfig = JSON.stringify(MFAConfig);
1233
- yield LoginUser._Repository.update({
1234
- MFAEnabled: user.MFAEnabled,
1235
- MFAConfig: user.MFAConfig,
1236
- }, {
1237
- where: {
1238
- UserId: userId,
1239
- },
1240
- transaction: dbTransaction,
1241
- });
1242
- return secretCode.otpauth_url;
1243
- });
1244
- }
1245
- verify2FASetup(userId, mfaToken, dbTransaction) {
1246
- return __awaiter(this, void 0, void 0, function* () {
1247
- const user = yield LoginUser._Repository.findOne({
1248
- where: {
1249
- UserId: userId,
1250
- },
1251
- });
1252
- if (!user) {
1253
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1254
- }
1255
- let userMFAConfig = null;
1256
- if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1257
- try {
1258
- userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1259
- }
1260
- catch (error) {
1261
- console.error('Invalid JSON string on MFAConfig:', error);
1262
- }
1263
- }
1264
- const isVerified = yield speakeasy.totp.verify({
1265
- secret: userMFAConfig.totp.secret,
1266
- encoding: 'base32',
1267
- token: mfaToken,
1268
- });
1269
- if (!isVerified) {
1270
- return false;
1271
- }
1272
- yield LoginUser._Repository.update({
1273
- MFAEnabled: 1,
1274
- }, {
1275
- where: {
1276
- UserId: userId,
1277
- },
1278
- transaction: dbTransaction,
1279
- });
1280
- const userSession = yield this._SessionService.retrieveUserSession(`${userId}`);
1281
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1282
- const systemLogin = userSession.systemLogins.find((e) => e.code === systemCode);
1283
- return `${userId}:${systemLogin.sessionId}`;
1284
- });
1285
- }
1286
- verify2FACode(userId, mfaToken, dbTransaction) {
1287
- return __awaiter(this, void 0, void 0, function* () {
1288
- const user = yield LoginUser._Repository.findOne({
1289
- where: {
1290
- UserId: userId,
1291
- },
1292
- transaction: dbTransaction,
1293
- });
1294
- if (!user) {
1295
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1296
- }
1297
- let userMFAConfig = null;
1298
- if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1299
- try {
1300
- userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1301
- }
1302
- catch (error) {
1303
- console.error('Invalid JSON string on MFAConfig:', error);
1304
- }
1305
- }
1306
- const isVerified = yield speakeasy.totp.verify({
1307
- secret: userMFAConfig.totp.secret,
1308
- encoding: 'base32',
1309
- token: mfaToken,
1310
- });
1311
- if (!isVerified) {
1312
- return false;
1313
- }
1314
- const userSession = yield this._SessionService.retrieveUserSession(`${userId}`);
1315
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1316
- const systemLogin = userSession.systemLogins.find((e) => e.code === systemCode);
1317
- return `${userId}:${systemLogin.sessionId}`;
1318
- });
1319
- }
1320
- addUserGroup(GroupCode, loginUser, dbTransaction) {
1321
- return __awaiter(this, void 0, void 0, function* () {
1322
- const group = yield LoginUser._GroupRepo.findOne({
1323
- where: {
1324
- GroupCode,
1325
- },
1326
- transaction: dbTransaction,
1327
- });
1328
- if (!group) {
1329
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Group Code');
1330
- }
1331
- const entityValueAfter = {
1332
- UserId: this.UserId,
1333
- GroupCode: group.GroupCode,
1334
- CreatedAt: new Date(),
1335
- CreatedById: loginUser.UserId,
1336
- UpdatedAt: new Date(),
1337
- UpdatedById: loginUser.UserId,
1338
- };
1339
- yield LoginUser._UserGroupRepo.create(entityValueAfter, {
1340
- transaction: dbTransaction,
1341
- });
1342
- const activity = new activity_history_1.Activity();
1343
- activity.ActivityId = activity.createId();
1344
- activity.Action = activity_history_1.ActionEnum.ADD;
1345
- activity.Description = 'Add User Group';
1346
- activity.EntityType = 'UserGroup';
1347
- activity.EntityId = group.GroupCode;
1348
- activity.EntityValueBefore = JSON.stringify({});
1349
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1350
- yield activity.create(loginUser.ObjectId, dbTransaction);
1351
- });
1352
- }
1353
- update(data, loginUser, dbTransaction) {
1354
- return __awaiter(this, void 0, void 0, function* () {
1355
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1356
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'User - Update');
1357
- if (!isPrivileged) {
1358
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to update user');
1359
- }
1360
- if (!this.UserId) {
1361
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'UserId is required');
1362
- }
1363
- if (data.Email !== this.Email || data.UserName !== this.UserName) {
1364
- yield LoginUser.checkUserInfoDuplicated(dbTransaction, {
1365
- Email: data.Email,
1366
- UserName: data.UserName,
1367
- });
1368
- }
1369
- if (data.BuildingCode) {
1370
- const building = yield group_entity_1.default.findOne({
1371
- where: {
1372
- Type: 'Building',
1373
- GroupCode: data.BuildingCode,
1374
- },
1375
- transaction: dbTransaction,
1376
- });
1377
- if (!building) {
1378
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Building Code');
1379
- }
1380
- const userBuilding = yield LoginUser._UserGroupRepo.findOne({
1381
- where: {
1382
- UserId: this.UserId,
1383
- },
1384
- include: [
1385
- {
1386
- model: group_entity_1.default,
1387
- where: {
1388
- Type: 'Building',
1389
- },
1390
- },
1391
- ],
1392
- transaction: dbTransaction,
1393
- });
1394
- if (userBuilding) {
1395
- yield LoginUser._UserGroupRepo.update({
1396
- GroupCode: data.BuildingCode,
1397
- UpdatedAt: new Date(),
1398
- UpdatedById: loginUser.UserId,
1399
- }, {
1400
- where: {
1401
- UserId: this.UserId,
1402
- GroupCode: userBuilding.GroupCode,
1403
- },
1404
- transaction: dbTransaction,
1405
- });
1406
- }
1407
- else {
1408
- yield LoginUser._UserGroupRepo.create({
1409
- UserId: this.UserId,
1410
- GroupCode: data.BuildingCode,
1411
- CreatedAt: new Date(),
1412
- CreatedById: loginUser.UserId,
1413
- UpdatedAt: new Date(),
1414
- UpdatedById: loginUser.UserId,
1415
- }, {
1416
- transaction: dbTransaction,
1417
- });
1418
- }
1419
- }
1420
- if (data.CompanyCode) {
1421
- const company = yield group_entity_1.default.findOne({
1422
- where: {
1423
- Type: 'Company',
1424
- GroupCode: data.CompanyCode,
1425
- },
1426
- transaction: dbTransaction,
1427
- });
1428
- if (!company) {
1429
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Company Code');
1430
- }
1431
- const userCompany = yield LoginUser._UserGroupRepo.findOne({
1432
- where: {
1433
- UserId: this.UserId,
1434
- },
1435
- include: [
1436
- {
1437
- model: group_entity_1.default,
1438
- where: {
1439
- Type: 'Company',
1440
- },
1441
- },
1442
- ],
1443
- transaction: dbTransaction,
1444
- });
1445
- if (userCompany) {
1446
- yield LoginUser._UserGroupRepo.update({
1447
- GroupCode: data.CompanyCode,
1448
- UpdatedAt: new Date(),
1449
- UpdatedById: loginUser.UserId,
1450
- }, {
1451
- where: {
1452
- UserId: this.UserId,
1453
- GroupCode: userCompany.GroupCode,
1454
- },
1455
- transaction: dbTransaction,
1456
- });
1457
- }
1458
- else {
1459
- yield LoginUser._UserGroupRepo.create({
1460
- UserId: this.UserId,
1461
- GroupCode: data.CompanyCode,
1462
- CreatedAt: new Date(),
1463
- CreatedById: loginUser.UserId,
1464
- UpdatedAt: new Date(),
1465
- UpdatedById: loginUser.UserId,
1466
- }, {
1467
- transaction: dbTransaction,
1468
- });
1469
- }
1470
- }
1471
- if (data.DepartmentCode) {
1472
- const department = yield group_entity_1.default.findOne({
1473
- where: {
1474
- Type: 'Department',
1475
- GroupCode: data.DepartmentCode,
1476
- },
1477
- transaction: dbTransaction,
1478
- });
1479
- if (!department) {
1480
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Department Code');
1481
- }
1482
- const userDepartment = yield LoginUser._UserGroupRepo.findOne({
1483
- where: {
1484
- UserId: this.UserId,
1485
- },
1486
- include: [
1487
- {
1488
- model: group_entity_1.default,
1489
- where: {
1490
- Type: 'Department',
1491
- },
1492
- },
1493
- ],
1494
- transaction: dbTransaction,
1495
- });
1496
- if (userDepartment) {
1497
- yield LoginUser._UserGroupRepo.update({
1498
- GroupCode: data.DepartmentCode,
1499
- UpdatedAt: new Date(),
1500
- UpdatedById: loginUser.UserId,
1501
- }, {
1502
- where: {
1503
- UserId: this.UserId,
1504
- GroupCode: userDepartment.GroupCode,
1505
- },
1506
- transaction: dbTransaction,
1507
- });
1508
- }
1509
- else {
1510
- yield LoginUser._UserGroupRepo.create({
1511
- UserId: this.UserId,
1512
- GroupCode: data.DepartmentCode,
1513
- CreatedAt: new Date(),
1514
- CreatedById: loginUser.UserId,
1515
- UpdatedAt: new Date(),
1516
- UpdatedById: loginUser.UserId,
1517
- }, {
1518
- transaction: dbTransaction,
1519
- });
1520
- }
1521
- }
1522
- const entityValueBefore = {
1523
- UserId: this.UserId,
1524
- UserName: this.UserName,
1525
- Email: this.Email,
1526
- Password: this.Password,
1527
- Status: this.Status,
1528
- DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
1529
- FirstLoginAt: this.FirstLoginAt,
1530
- LastLoginAt: this.LastLoginAt,
1531
- MFAEnabled: this.MFAEnabled,
1532
- MFAConfig: this.MFAConfig,
1533
- RecoveryEmail: this.RecoveryEmail,
1534
- FailedLoginAttemptCount: this.FailedLoginAttemptCount,
1535
- LastFailedLoginAt: this.LastFailedLoginAt,
1536
- LastPasswordChangedAt: this.LastPasswordChangedAt,
1537
- NeedToChangePasswordYN: this.NeedToChangePasswordYN,
1538
- CreatedById: this.CreatedById,
1539
- CreatedAt: this.CreatedAt,
1540
- UpdatedById: this.UpdatedById,
1541
- UpdatedAt: this.UpdatedAt,
1542
- };
1543
- this.UserName = data.UserName;
1544
- this.Email = data.Email;
1545
- this.Status = data.Status;
1546
- this.RecoveryEmail = data.RecoveryEmail;
1547
- this.UpdatedAt = new Date();
1548
- this.UpdatedById = loginUser.UserId;
1549
- yield LoginUser._Repository.update({
1550
- UserName: this.UserName,
1551
- Email: this.Email,
1552
- Status: this.Status,
1553
- RecoveryEmail: this.RecoveryEmail,
1554
- UpdatedById: this.UpdatedById,
1555
- UpdatedAt: this.UpdatedAt,
1556
- }, {
1557
- where: {
1558
- UserId: this.UserId,
1559
- },
1560
- transaction: dbTransaction,
1561
- });
1562
- const entityValueAfter = {
1563
- UserId: this.UserId,
1564
- UserName: this.UserName,
1565
- Email: this.Email,
1566
- Password: this.Password,
1567
- Status: this.Status,
1568
- DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
1569
- FirstLoginAt: this.FirstLoginAt,
1570
- LastLoginAt: this.LastLoginAt,
1571
- MFAEnabled: this.MFAEnabled,
1572
- MFAConfig: this.MFAConfig,
1573
- RecoveryEmail: this.RecoveryEmail,
1574
- FailedLoginAttemptCount: this.FailedLoginAttemptCount,
1575
- LastFailedLoginAt: this.LastFailedLoginAt,
1576
- LastPasswordChangedAt: this.LastPasswordChangedAt,
1577
- NeedToChangePasswordYN: this.NeedToChangePasswordYN,
1578
- CreatedById: this.CreatedById,
1579
- CreatedAt: this.CreatedAt,
1580
- UpdatedById: this.UpdatedById,
1581
- UpdatedAt: this.UpdatedAt,
1582
- };
1583
- const activity = new activity_history_1.Activity();
1584
- activity.ActivityId = activity.createId();
1585
- activity.Action = activity_history_1.ActionEnum.UPDATE;
1586
- activity.Description = 'Update User';
1587
- activity.EntityType = 'LoginUser';
1588
- activity.EntityId = this.UserId.toString();
1589
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1590
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1591
- yield activity.create(loginUser.ObjectId, dbTransaction);
1592
- return this;
1593
- });
1594
- }
1595
139
  }
1596
140
  exports.LoginUser = LoginUser;
1597
- LoginUser._Repository = new user_repository_1.UserRepository();
1598
- LoginUser._LoginHistoryRepository = new login_history_repository_1.LoginHistoryRepository();
1599
- LoginUser._UserGroupRepo = new user_group_repository_1.UserGroupRepository();
1600
- LoginUser._UserPrivilegeRepo = new user_privilege_repository_1.UserPrivilegeRepository();
1601
- LoginUser._UserObjectPrivilegeRepo = new user_object_privilege_repository_1.UserObjectPrivilegeRepository();
1602
- LoginUser._GroupObjectPrivilegeRepo = new group_object_privilege_repository_1.GroupObjectPrivilegeRepository();
1603
- LoginUser._SystemRepository = new system_repository_1.SystemRepository();
1604
- LoginUser._UserSystemAccessRepo = new user_system_access_repository_1.UserSystemAccessRepository();
1605
- LoginUser._GroupSystemAccessRepo = new group_system_access_repository_1.GroupSystemAccessRepository();
1606
- LoginUser._GroupRepo = new group_repository_1.GroupRepository();
1607
141
  //# sourceMappingURL=login-user.js.map