All files / src/services user.service.ts

10.12% Statements 33/326
0% Branches 0/464
3.13% Functions 1/32
9.63% Lines 31/322

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085  1x 1x 1x 1x 1x 1x 1x 1x   1x   1x                       1x 1x 1x 1x 1x 1x     1x   1x     1x   1x       18x   18x   18x   18x   18x   18x   18x   18x   18x   18x   18x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import {AnyObject} from '@logchain/types';
import {bind, /* inject, */ BindingScope, inject, service} from '@loopback/core';
import {EntityNotFoundError, Filter, FilterBuilder, Options, repository, Where} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {SecurityBindings, securityId} from '@loopback/security';
import {merge} from 'lodash';
import {BaseService, CompanyService} from '.';
import {AttributeKeys, AwsCognitoService, AwsServiceBindings, Claim, UserProfile} from '../components/aws';
import {AwsConfigs, Constants, LogChainConfigs} from '../configs';
import {UserDto} from '../dtos';
import {BaseResponses, Company, Role, Status, User, UserActivity, UserSetting, UserWithRelations} from '../models';
 
import {
  CompanyPartyRepository,
  CompanyPersonaRepository,
  CompanyRepository,
  RFIDUserMappingRepository,
  RoleRepository,
  RoleRightsRepository,
  UserActivityRepository,
  UserRepository,
  UserViewRepository,
} from '../repositories';
import {UserView} from '@logchain/models/views';
import AWS from 'aws-sdk';
import {MicrosoftGraphService} from './microsoft-graph.service';
import {RFID_STORE} from '@logchain/store/rfid-session.store';
import axios from 'axios';
const jwt = require('jsonwebtoken');
const jwkToPem = require('jwk-to-pem');
 
@bind({scope: BindingScope.TRANSIENT})
export class UserService extends BaseService<User> {
  @inject(SecurityBindings.USER, {optional: true})
  public current_user: UserProfile;
 
  @service(CompanyService)
  public company_service: CompanyService;
  @service(MicrosoftGraphService)
  public microsoft_graph_service: MicrosoftGraphService;
 
  constructor(
    @repository(UserRepository)
    public user_repo: UserRepository,
    @repository(UserViewRepository)
    public userview_repo: UserViewRepository,
    @repository(CompanyRepository)
    public comp_repo: CompanyRepository,
    @repository(RoleRepository)
    public role_repo: RoleRepository,
    @repository(RoleRightsRepository)
    public role_rights_repo: RoleRightsRepository,
    @repository(CompanyPersonaRepository)
    public comp_persona_repo: CompanyPersonaRepository,
    @repository(UserActivityRepository)
    public user_activity_repo: UserActivityRepository,
    @repository(CompanyPartyRepository)
    public comp_party_repo: CompanyPartyRepository,
    @repository(RFIDUserMappingRepository)
    public rfid_user_mapping_repo: RFIDUserMappingRepository,
    @inject(AwsServiceBindings.COGNITO_SERVICE)
    public cognito_service: AwsCognitoService,
  ) {
    super();
  }
 
  /**
   * Get user by id or identifier
   * @param id The user id
   * @param filter The filter
   * @returns Promise<User | null>
   */
  async getByIdOrIdentifier(id: number | string, options?: Options): Promise<UserWithRelations> {
    this.addWhereIdOrIdentifier(id);
 
    this.addExtraFilter(this.filter_builder, {
      activity: true,
      is_private: options?.is_private,
    });
    if (!options?.is_private) {
      this.filter_builder.impose({
        company_id: this.current_user.company_id,
      });
      this.filter_builder.impose({
        status: {neq: Status.User.Deleted},
      });
    }
    const filter_builder = new FilterBuilder<UserView>();
    filter_builder.filter = this.filter_builder.filter as AnyObject;
    // find user.
    const user = await this.userview_repo.findOne(filter_builder.build());
 
    if (!user) {
      throw new EntityNotFoundError(this.userview_repo.entityClass, id);
    }
 
    // get identity info to show user
    if (options?.profile) {
      if (process.env.HLF_BY_PASS === 'true') {
        console.log('HLF bypass enabled - skip wallet check');
 
        user.blockchain_identity = undefined;
      } else {
        user.blockchain_identity = await this.ca_service.getInfoFromIdentity(user.identifier);
      }
 
      user.role.modules = await this.role_repo.getPermissions();
    }
    return user;
  }
 
  /**
   * Get the user by email
   * @param email The user email
   * @returns Promise<User | null>
   */
  async getUserByEmail(email: string): Promise<User | null> {
    return this.userview_repo.findOne({
      where: {
        contact_email: email,
      },
    });
  }
 
  /**
   * Get the other users by email
   * @param id The user ID
   * @param email The user email
   * @returns Promise<User | null>
   */
  async getOtherUsersByEmail(id: number, email: string): Promise<User | null> {
    return this.userview_repo.findOne({
      where: {
        id: {neq: id},
        contact_email: email,
      },
    });
  }
 
  /**
   * Get the user by phone number
   * @param phone The phone number
   * @returns Promise<boolean>
   */
  async getUserByPhoneNumber(phone: string): Promise<User | null> {
    return this.userview_repo.findOne({
      where: {
        contact_number: phone,
        status: Status.User.Active,
        phone_number_verified: true,
      },
    });
  }
 
  /**
   * Delete user by id or identifier
   * @param id The user id
   */
  async deleteByIdOrIdentifier(id: number | string, options?: Options) {
    this.addWhereIdOrIdentifier(id);
    if (!options?.is_private) {
      this.filter_builder.impose({
        company_id: this.current_user.company_id,
      });
      this.filter_builder.impose({
        name: {neq: '[Unknown removed user]'},
      });
    }
 
    const filter_builder = new FilterBuilder<UserView>();
    filter_builder.filter = this.filter_builder.filter as AnyObject;
    const user_delete = await this.userview_repo.findOne(filter_builder.build());
 
    if (!user_delete) {
      throw new HttpErrors.BadRequest('User not found!');
    }
    if (!options?.profile) {
      // Admin delete user
      if (user_delete.status === Status.User.Active) {
        throw new HttpErrors.BadRequest(`Don\'t allow to delete, current status is ${user_delete.status}`);
      }
    } else {
      // Self deleted
      const admin = await this.userview_repo.findOne({
        where: {
          is_admin: true,
          company_id: this.current_user.company_id,
        },
      });
      if (admin) {
        // send email inform admin.
        if (options?.profile) {
          await this.ses_service.sendTemplatedEmail(Constants.Email.InformAdminOfCompanyAfterDeactivate, admin, {
            username: user_delete.name,
          });
        }
      }
    }
 
    await this.user_repo.deleteAll(this.filter_builder.build().where, {
      deleted_user: user_delete,
      user_view_repo: this.user_view_repo,
    });
    // send email inform user.
    if (process.env.HLF_BY_PASS !== 'true') {
      await this.ses_service.sendTemplatedEmail(Constants.Email.InformUserAfterDelete, user_delete, {
        username: user_delete.name,
      });
    } else {
      console.log('HLF bypass enabled - skip SES email');
    }
    return user_delete;
  }
 
  /**
   * Creates user service
   * @param userDto
   * @returns create
   */
  async create(userDto: UserDto, options?: Options): Promise<User> {
    // if company_id not exists, it should be the same with the company of current_user
    if (!userDto.company_id) {
      userDto.company_id = this.current_user.company_id;
      // Mark in case the user is created by admin
      options = options ? {...options, is_private: true} : {is_private: true};
    }
 
    // validate user info
    const company_name = await this._validateUserInfo(userDto, options?.is_private);
    if (!company_name) {
      throw new HttpErrors.BadRequest(`Company name not found for user ${userDto.contact_email}`);
    }
 
    const cognitoUser = await this.cognito_service.createUser({
      ...userDto,
      company_name,
    } as unknown as User);
    const sub = this.cognito_service.retrieveAttributeByName(AttributeKeys.Sub, cognitoUser.User?.Attributes);
 
    if (!sub) {
      throw new HttpErrors.BadRequest(`Sub not found for user ${userDto.contact_email}`);
    }
 
    // create the user.
    userDto.sub = sub.Value;
    const user = await this.user_repo.create(userDto);
 
    // try {
    //   if (user.contact_email) {
    //     const tenantUser = await this.microsoft_graph_service.findUser(user.contact_email);
 
    //     if (!tenantUser) {
    //       console.log('Inviting user to Microsoft tenant:', user.contact_email);
 
    //       await this.microsoft_graph_service.inviteUser(user.contact_email);
 
    //       console.log('Microsoft invite success');
    //     } else {
    //       console.log('User already exists in Microsoft tenant');
    //     }
    //   }
    // } catch (msError) {
    //   console.error('Microsoft tenant invite failed:', msError);
    // }
 
    return this.userview_repo.findById(user.id);
  }
 
  /**
   * Update user by id or identifier
   * @param userDto The User DTO
   */
  async updateByIdOrIdentifier(id: number | string, user: Partial<User>, options?: Options) {
    const {role_id, status} = user;
    let {contact_email, contact_number} = user;
    const {contact_number_overwrite = false} = user as AnyObject;
 
    this.addWhereIdOrIdentifier(id);
 
    // can not change status to invite
    if (status === Status.User.Invite) {
      throw new HttpErrors.BadRequest(`Can not change status to invite ${status}`);
    }
 
    if (user?.company_id) {
      if (this.current_user.role_id !== LogChainConfigs.LogChainAdminRoleId && !options?.is_private) {
        throw new HttpErrors.BadRequest(`User do not allowed.`);
      }
    }
 
    if (!options?.is_private) {
      this.filter_builder.impose({
        company_id: this.current_user.company_id,
      });
      this.filter_builder.impose({
        status: {neq: Status.User.Deleted},
      });
    }
 
    // find the user
    const filter_builder = new FilterBuilder<UserView>();
    filter_builder.filter = this.filter_builder.filter as AnyObject;
    const userInst = await this.userview_repo.findOne(filter_builder.build());
    if (!userInst) {
      throw new HttpErrors.NotFound(`User not found ${id}`);
    }
 
    // don't validate contact_email if it the same with current contact_email
    if (contact_email === userInst.contact_email) {
      contact_email = '';
    }
 
    // don't validate contact_number if it the same with current contact_number
    if (contact_number === userInst.contact_number) {
      contact_number = '';
    }
 
    // delete old avatar's user in s3
    if (user.avatar && user.avatar !== userInst.avatar) {
      await this.s3_service.getObjectMetadata(user.avatar);
      super.cleanUpStorage(userInst.avatar);
    }
 
    // validate user info
    await this._validateUserInfo(
      {
        ...user,
        company_id: userInst.company_id,
        is_admin: user.is_admin,
      } as UserDto,
      options?.is_private,
      contact_number_overwrite,
      userInst,
    );
 
    // update user information to cognito
    const rsUpdated = await this.cognito_service.updateUser(userInst.contact_email, user);
 
    // Reset duplicated users by phone
    if (rsUpdated) {
      if (contact_number && contact_number_overwrite) {
        await this.user_repo.updateAll(
          {
            contact_number: Constants.fakePhoneNumber,
          },
          {
            contact_number: contact_number,
          },
        );
      }
 
      // update the user.
      await this.user_repo.updateAll(user, this.filter_builder.build().where);
 
      // enable user in cognito.
      if (status === Status.User.Active && userInst.status !== Status.User.Active) {
        await this.cognito_service.enableUser(userInst.contact_email);
      }
      // disable user in cognito.
      if (status === Status.User.Inactive && userInst.status !== Status.User.Inactive) {
        if (process.env.HLF_BY_PASS === 'true') {
          console.log('HLF bypass enabled - skip SES email');
 
          await this.cognito_service.disableUser(userInst.contact_email);
        } else {
          await Promise.all([
            this.cognito_service.disableUser(userInst.contact_email),
            this.ses_service.sendTemplatedEmail(Constants.Email.InformUserAfterDeactivate, userInst, {
              username: userInst.name,
            }),
          ]);
        }
      }
    }
 
    return userInst;
  }
 
  /**
   * Update new settings for the user.
   * @param settings The new settings.
   * @param options The options.
   */
  async updateSettings(settings: Partial<UserSetting>, options?: Options) {
    const new_settings = merge(this.current_user.settings, settings);
    return this.user_repo.updateById(this.current_user.id, {
      settings: new_settings,
    });
  }
 
  /**
   * Validates user info
   * @param contact_email The user email
   * @param contact_number The user phone
   * @param role_id The role Id
   */
  private async _validateUserInfo(
    userDto: UserDto,
    is_private?: boolean,
    contact_number_overwrite?: boolean,
    userInst?: User,
  ) {
    const {contact_email, role_id, company_id, contact_number, is_admin} = userDto;
 
    if (contact_email) {
      // email must not exists.
      let existsEmail = await this.getUserByEmail(contact_email);
      if (userInst !== undefined) {
        // For Edit user case.
        existsEmail = await this.getOtherUsersByEmail(userInst.id, contact_email);
      }
 
      if (existsEmail) {
        throw new HttpErrors.BadRequest(`The email already exists: ${contact_email}`);
      }
    }
 
    if (contact_number && !contact_number_overwrite) {
      // phone number must not exists.
      const existsNum = await this.getUserByPhoneNumber(contact_number);
      if (existsNum) {
        throw new HttpErrors.BadRequest(`The phone number already exists: ${contact_number}`);
      }
    }
 
    if (typeof role_id === 'number') {
      // role must exists and active;
      const filterBuilder = new FilterBuilder<Role>();
      filterBuilder.where({
        id: role_id,
      });
 
      if (this.current_user.role_id !== LogChainConfigs.LogChainAdminRoleId && !is_private) {
        // Public Request
        filterBuilder.impose({private: false});
      }
      const filter = filterBuilder.build();
      const existsRole = await this.role_repo.findOne(filter);
      if (!existsRole || !existsRole.status) {
        throw new HttpErrors.BadRequest(`The role id not exists: ${role_id}`);
      }
 
      // Private call, should not change other company into logchain
      if (this.current_user.id !== LogChainConfigs.LogChainRootAdminId) {
        if (
          existsRole?.private &&
          (company_id !== LogChainConfigs.LogChainCompanyId || !LogChainConfigs.SaeslCompanyId.includes(company_id))
        ) {
          throw new HttpErrors.BadRequest(`The role does not exist`);
        }
      }
    }
 
    if (!is_private) {
      if (this.current_user.is_admin === false && userDto.is_admin === true) {
        throw new HttpErrors.BadRequest(`User do not allowed to change admin status.`);
      }
 
      if (is_admin && userDto.status === Status.User.Inactive) {
        throw new HttpErrors.BadRequest(`Admin users cannot have status set to Inactive.`);
      }
    }
 
    if (userInst) {
      // If there is no admin, we need to check if the user is remove off admin
      if (is_admin !== undefined) {
        const numAdmin = await this.user_repo.count({
          company_id,
          is_admin: true,
        });
        if (numAdmin.count === 1 && userInst.is_admin && userInst.is_admin !== is_admin && is_admin !== undefined) {
          throw new HttpErrors.BadRequest(`The company must at least has one admin: ${company_id}`);
        }
      }
    }
 
    if (!is_private && typeof company_id === 'number') {
      // company must exists.
      const existsCo = await this.company_service.getByIdOrIdentifier(company_id);
 
      // company must active or invite
      if (existsCo.status !== Status.Company.Active) {
        throw new HttpErrors.BadRequest(`The company is not active: ${company_id}`);
      }
 
      // Validate licences
      if (!is_private && this.current_user.role_id !== LogChainConfigs.LogChainAdminRoleId) {
        const currentRole = await this.role_repo.findById(role_id);
        const curLicence = existsCo?.licences?.length ? existsCo.licences[0] : null;
        if (!userInst) {
          // For create user case and not admin
          if (!curLicence) {
            throw new HttpErrors.BadRequest(Constants.errorMessage['no-licence-for-admin']);
          } else if (currentRole.collar_type === Constants.CollarType.White) {
            if ((curLicence?.white_collar_users ?? 0) <= existsCo.users_summary.white_actived) {
              throw new HttpErrors.BadRequest(Constants.errorMessage['white-users-limit-reached']);
            }
          } else if (currentRole.collar_type === Constants.CollarType.Blue) {
            if ((curLicence?.blue_collar_users ?? 0) <= existsCo.users_summary.blue_actived) {
              throw new HttpErrors.BadRequest(Constants.errorMessage['blue-users-limit-reached']);
            }
          }
        }
        // For edit user case, and company admin want to change user role to another one.
        if (userInst && userDto.role_id !== userInst.role_id) {
          if (currentRole.collar_type === Constants.CollarType.White) {
            if ((curLicence?.white_collar_users ?? 0) <= existsCo.users_summary.white_actived) {
              throw new HttpErrors.BadRequest(Constants.errorMessage['white-users-limit-reached']);
            }
          } else if (currentRole.collar_type === Constants.CollarType.Blue) {
            if ((curLicence?.blue_collar_users ?? 0) <= existsCo.users_summary.blue_actived) {
              throw new HttpErrors.BadRequest(Constants.errorMessage['blue-users-limit-reached']);
            }
          }
        }
      }
 
      return existsCo.name;
    }
  }
 
  /**
   * Get array users based on filter.
   * @param filter
   */
  async find(options?: Options): Promise<BaseResponses<UserView>> {
    const filter_builder = new FilterBuilder<UserView>();
    filter_builder.filter = this.filter_builder.filter as AnyObject;
    this.addExtraFilter(filter_builder);
    if (!options?.is_private) {
      filter_builder.impose({
        company_id: this.current_user.company_id,
      });
      filter_builder.impose({
        status: {neq: Status.User.Deleted},
      });
    }
    return this.userview_repo.findWithPaging(filter_builder.build());
  }
 
  /**
   * Add extra filter for user
   * @param filterBuilder The filter builder instance
   * @param options The options
   * @return Filter
   */
  addExtraFilter(filterBuilder: FilterBuilder, options?: Options): Filter<AnyObject> {
    // add creator, modifier
    this._addIncludeCreator(this.filter_builder);
    this._addIncludeModifier(this.filter_builder);
 
    filterBuilder.include({
      relation: 'role',
      scope: {
        fields: {
          id: true,
          name: true,
        },
      },
    });
 
    // get more activities for the user
    // limit 20 item and order by activity_date
    if (options?.activity) {
      filterBuilder.include({
        relation: 'activities',
        scope: {
          limit: Constants.ActivitiesLimit,
          order: ['activity_date DESC'],
          fields: {
            activity: false,
          },
        },
      });
    }
 
    if (options?.is_private) {
      filterBuilder.include({
        relation: 'company',
        scope: {
          fields: {
            id: true,
            identifier: true,
            name: true,
            address: true,
          },
        },
      });
    } else {
      filterBuilder.include({
        relation: 'company',
        scope: {
          fields: {
            id: true,
            identifier: true,
            name: true,
          },
        },
      });
    }
    return filterBuilder.build();
  }
 
  private async verifyMicrosoftToken(token: string): Promise<any> {
    const decodedHeader: any = jwt.decode(token, {
      complete: true,
    });
 
    if (!decodedHeader?.header?.kid) {
      throw new HttpErrors.Unauthorized('Invalid Microsoft token');
    }
 
    const {data} = await axios.get('https://login.microsoftonline.com/common/discovery/v2.0/keys');
 
    const signingKey = data.keys.find((k: any) => k.kid === decodedHeader.header.kid);
 
    if (!signingKey) {
      throw new HttpErrors.Unauthorized('Microsoft signing key not found');
    }
 
    const pem = jwkToPem(signingKey);
 
    return jwt.verify(token, pem, {
      algorithms: ['RS256'],
    });
  }
 
  async loginWithMicrosoft(token: string, redirectUrl?: string): Promise<any> {
    try {
      const decoded: any = await this.verifyMicrosoftToken(token);
 
      const email = (
        decoded?.email ||
        decoded?.preferred_username ||
        decoded?.upn ||
        decoded?.unique_name
      )?.toLowerCase();
 
      // console.log('Microsoft decoded token:', decoded);
 
      if (!email) {
        throw new HttpErrors.Unauthorized('Microsoft email not found!');
      }
 
      const user = await this.getUserByEmail(email);
 
      if (!user) {
        throw new HttpErrors.Forbidden('User does not exist!');
      }
 
      try {
        const tenantUser = await this.microsoft_graph_service.findUser(email);
 
        if (!tenantUser) {
          console.log('Inviting verified Microsoft user:', email);
 
          await this.microsoft_graph_service.inviteUser(email, redirectUrl);
 
          console.log('Microsoft invite success');
        } else {
          console.log('User already exists in tenant');
        }
      } catch (msErr) {
        console.error('Microsoft invite failed', msErr);
      }
 
      if (user.status !== Status.User.Active) {
        throw new HttpErrors.Unauthorized('User not active!');
      }
 
      const cognito = new AWS.CognitoIdentityServiceProvider();
 
      const auth = await cognito
        .adminInitiateAuth({
          UserPoolId: AwsConfigs.cognitoConfig.userPoolId,
 
          ClientId: AwsConfigs.cognitoConfig.clientId,
 
          AuthFlow: 'CUSTOM_AUTH',
 
          AuthParameters: {
            USERNAME: email,
          },
 
          ClientMetadata: {
            login_type: 'microsoft',
          },
        })
        .promise();
 
      return auth.AuthenticationResult;
    } catch (err: any) {
      console.error(err);
 
      throw new HttpErrors.Unauthorized(err.message || 'Microsoft login failed');
    }
  }
 
  async loginWithRFID(uid: string): Promise<any> {
    try {
      console.log('RFID UID:', uid);
 
      const mapping = await this.rfid_user_mapping_repo.findOne({
        where: {
          uid: uid.toUpperCase(),
        },
      });
 
      if (!mapping) {
        throw new HttpErrors.Unauthorized(`RFID card UID : ${uid} not registered`);
      }
 
      const user = await this.getByIdOrIdentifier(mapping.user_identifier, {
        is_private: true,
      });
 
      // const user = await this.getByIdOrIdentifier('22e4adf6-ca60-4d45-93ad-ffe0e8c88e7e');
 
      if (!user) {
        throw new HttpErrors.Forbidden('User not provisioned');
      }
 
      const sessionId = RFID_STORE.create(user.contact_email);
 
      return {
        sessionId,
      };
    } catch (err: any) {
      console.error(err);
 
      throw new HttpErrors.Unauthorized(err.message || 'RFID login failed');
    }
  }
 
  async exchangeRFIDSession(sessionId: string): Promise<any> {
    const session = RFID_STORE.get(sessionId);
 
    if (!session) {
      throw new HttpErrors.Unauthorized('Invalid session');
    }
 
    // if (Date.now() - session.createdAt > 15000) {
    //   RFID_STORE.delete(sessionId);
 
    //   throw new HttpErrors.Unauthorized('Session expired');
    // }
 
    // RFID_STORE.delete(sessionId);
 
    const cognito = new AWS.CognitoIdentityServiceProvider();
 
    const auth = await cognito
      .adminInitiateAuth({
        UserPoolId: AwsConfigs.cognitoConfig.userPoolId,
 
        ClientId: AwsConfigs.cognitoConfig.clientId,
 
        AuthFlow: 'CUSTOM_AUTH',
 
        AuthParameters: {
          USERNAME: session.email,
        },
 
        ClientMetadata: {
          login_type: 'rfid',
        },
      })
      .promise();
 
    return auth.AuthenticationResult;
  }
 
  /**
   * Find and convert sub to user profile.
   * @param payload The payload.
   */
  async convertToUserProfile(payload: Claim, token?: string): Promise<UserProfile | undefined> {
    let email = payload.email;
 
    if (!email && token) {
      try {
        const userInfo = await this.cognito_service.getUserInfo(token);
        email = userInfo.email;
      } catch (e) {
        console.warn('Cannot fetch userInfo from Cognito');
      }
    }
 
    let user = (await this.userview_repo.findBySub(payload.sub)) as UserWithRelations | null;
 
    if (!user && email) {
      user = await this.getUserByEmail(email);
 
      if (!user) {
        throw new HttpErrors.Unauthorized('User does not exist');
      }
      // await this.user_repo.updateById(user.id, {sub: payload.sub});
    }
 
    if (!user) {
      throw new HttpErrors.Forbidden('User not provisioned');
    }
 
    if (user.status !== Status.User.Active) {
      throw new HttpErrors.Unauthorized('User not active!');
    }
 
    // Check company status
    if (user.company?.status !== Status.Company.Active) {
      throw new HttpErrors.Unauthorized(`Company is not active!`);
    }
 
    const comp = await this.comp_persona_repo.find({
      fields: {
        company_id: true,
        persona_id: true,
      },
      where: {
        company_id: user?.company_id,
      },
    });
 
    // Check company Licence
    const havePersonaLogChain = comp.find(persona => persona.persona_id === Constants.Persona.LogChain);
    if (user.company.id !== LogChainConfigs.LogChainCompanyId && !havePersonaLogChain) {
      if (
        !user.company?.licences ||
        user.company?.licences?.length === 0 ||
        user.company?.licences[0].status !== Status.CompanyLicence.Active ||
        user.company?.licences[0].end_date < new Date()
      ) {
        throw new HttpErrors.Unauthorized(
          user.is_admin
            ? Constants.errorMessage['no-licence-for-admin']
            : Constants.errorMessage['no-licence-for-user'],
        );
      }
    }
 
    // tracking login time.
    this._trackingLoginDate(user, payload);
 
    return {
      [securityId]: user.identifier,
      identifier: user.identifier,
      id: user.id,
      company_id: user.company_id,
      company_identifier: user.company?.identifier ?? '',
      company_name: user.company?.name ?? '',
      email: user?.contact_email,
      number: user?.contact_number,
      name: user?.name,
      role_id: user?.role_id,
      company_personas: comp,
      timezone: user.company?.timezone ?? '',
      status: user.status,
      company_status: user.company?.status ?? 0,
      is_admin: user.is_admin ?? false,
      settings: user.settings,
      sub: user.sub,
      company_parties: await this.comp_party_repo.find({where: {company_id: user.company_id}}),
    } as unknown as UserProfile;
  }
 
  /**
   * Tracking time user login.
   * @param user The user information.
   * @param auth_time The auth time.
   */
  private _trackingLoginDate(user: User, payload: AnyObject): void {
    let {auth_time = 0} = payload;
    auth_time = auth_time * 1000;
    if (user.login_date && auth_time === +user.login_date) {
      return;
    }
    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    setImmediate(async () => {
      await Promise.all([
        this.user_repo.updateById(user.id, {login_date: auth_time}),
        // this.user_activity_repo.create({
        //   user_id: user.id,
        //   table_name: User.definition.settings['postgresql'].table,
        //   feature_id: user.id.toString(),
        //   action: 'Login',
        //   description: `User ${user.name} logs in on the application`,
        // })
      ]);
    });
  }
 
  /**
   * Activate the user after change temporary password.
   * @param sub The sub from Cognito.
   */
  async activateUser(sub: string): Promise<void> {
    const user = (await this.userview_repo.findBySub(sub)) as UserWithRelations;
    if (!user) {
      throw new HttpErrors.NotFound(`User with sub ${sub} not found`);
    }
 
    if (user.status === Status.User.Active) {
      return;
    }
 
    if (user.status !== Status.User.Invite) {
      throw new HttpErrors.BadRequest(`Status user must be invited. Current status is ${user.status}`);
    }
 
    // update status to active.
    await this.updateByIdOrIdentifier(
      user.id,
      {
        status: Status.User.Active,
      },
      {is_private: true}, // we call inside code.
    );
 
    const perms = await this.user_repo.execute('SELECT * FROM get_permissions_by_role($1, $2);', [
      user.role_id,
      user.company_id,
    ]);
 
    if (!perms?.length) {
      return;
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const features = perms.map((perm: any) => {
      return perm.features;
    });
 
    // invoke chaincode CreateActor
    await this.cc_service.invoke('CreateActor', {
      actorId: user.id,
      actorIdentifier: user.identifier,
      actorSub: user.sub,
      email: user.contact_email,
      companyId: user.company_id,
      features: features.flat(Infinity),
      name: user.name,
    });
  }
 
  /**
   * Builds the query for user.
   * @param q The query string.
   */
  async buildSearchQuery(q?: string) {
    if (!q) {
      return;
    }
 
    const ilike_value = this.buildILikeValue(q);
    // FILTER: name OR contact_email Should be a LIKE search
    this.filter_builder.impose({
      or: [
        {
          name: ilike_value,
        },
        {
          contact_email: ilike_value,
        },
      ],
    });
  }
 
  /**
   * Find roles with pagination based on filter.
   * @param itemFilter The filter builder.
   * @returns The response with array of roles.
   */
  async findFiltersRoles(itemFilter: FilterBuilder<Role>) {
    return this.role_repo.findWithPaging(itemFilter.build());
  }
 
  /**
   * Find companies with pagination based on filter.
   * @param itemFilter The filter builder.
   * @returns The response with array of companies.
   */
  async findFiltersCompanies(itemFilter: FilterBuilder<Company>) {
    return this.comp_repo.findWithPaging(itemFilter.build());
  }
 
  /**
   * Sign out user from API server
   * @param  {AnyObject} data
   * @returns Promise
   */
  async signout(data: AnyObject): Promise<void> {
    const user = (await this.userview_repo.findById(this.current_user.id)) as UserWithRelations;
 
    if (user) {
      if (user.status !== Status.User.Active) {
        throw new HttpErrors.BadRequest(`Status user must be activated. Current status is ${user.status}`);
      }
 
      // For Root admin login as user.
      if (user.id === LogChainConfigs.LogChainRootAdminId) {
        await this.updateByIdOrIdentifier(
          user.id,
          {
            company_id: LogChainConfigs.LogChainCompanyId,
            role_id: LogChainConfigs.LogChainAdminRoleId,
          },
          {is_private: true},
        );
      }
 
      const {expired = false} = data;
      if (expired) {
        this._trackingLogoutDate(user, {
          reason: `User ${user.name} session expired and was automatically logged out the application`,
        });
      } else {
        this._trackingLogoutDate(user, {reason: `User ${user.name} logs out the application`});
      }
    }
  }
 
  /**
   * Reset user password
   * @param  {AnyObject} data
   * @returns Promise
   */
  async resendTemporaryPassword(data: AnyObject): Promise<void> {
    try {
      const user = await this.user_view_repo.findOne({
        where: {identifier: data.identifier, status: Status.User.Invite},
      });
      if (!user) {
        throw new HttpErrors.BadRequest(`User not found or User status invalid.`);
      }
      await this.cognito_service.resendTemporaryPassword(user);
    } catch (e) {
      console.error(e);
    }
  }
 
  /**
   * Process deleted accounts.
   * This function is run every 24 hours to remove deleted accounts.
   * It's called by a cron job.
   * @returns Promise
   */
  async processDeletedAccounts(): Promise<void> {
    const deletedUsers = await this.user_view_repo.find({
      where: {
        name: {neq: '[Unknown removed user]'},
        status: Status.User.Deleted,
        modified_date: {lt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 14)}, // After 2 weeks
      },
    });
    for (const deletedUser of deletedUsers) {
      if (!this.current_user) {
        this.current_user = deletedUser as unknown as UserProfile;
      }
      await this.deleteByIdOrIdentifier(deletedUser.id, {profile: true});
    }
  }
 
  /**
   * Tracking time user logout.
   * @param user The user information.
   * @param auth_time The auth time.
   */
  private _trackingLogoutDate(user: User, payload: AnyObject): void {
    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    setImmediate(async () => {
      await Promise.all([
        this.user_activity_repo.create({
          user_id: user.id,
          table_name: User.definition.settings['postgresql'].table,
          feature_id: user.id.toString(),
          action: 'Logout',
          description: payload?.reason ?? '',
        }),
      ]);
    });
  }
 
  async forgotPassword(username: string) {
    return this.cognito_service.forceVerifyAndResetPassword(username);
  }
}