All files / src/components/aws/services aws-cognito.service.ts

15.59% Statements 29/186
1.96% Branches 2/102
4.88% Functions 2/41
15.68% Lines 29/185

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    1x 1x   1x                           1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                 1x                       1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
import {AuthenticationStrategyOptions} from '@logchain/auth-strategies';
import {AnyObject} from '@logchain/types';
import {inject} from '@loopback/core';
import {HttpErrors, RedirectRoute} from '@loopback/rest';
import {Principal} from '@loopback/security';
import AWS from 'aws-sdk';
import {
  AdminCreateUserRequest,
  AdminCreateUserResponse,
  AdminDeleteUserRequest,
  AdminDisableUserRequest,
  AdminEnableUserRequest,
  AdminUpdateUserAttributesRequest,
  AdminUpdateUserAttributesResponse,
  AttributeListType,
  AttributeType,
  ListUsersRequest,
  ListUsersResponse,
} from 'aws-sdk/clients/cognitoidentityserviceprovider';
import fetch from 'node-fetch';
import {promisify} from 'util';
import {AwsConfigs, Constants} from '../../../configs';
import {User, UserSetting} from '../../../models';
import {AwsServiceBindings} from '../keys';
import {AwsSesService} from './aws-ses.service';
const jwt = require('jsonwebtoken');
const jwkToPem = require('jwk-to-pem');
const verifyPromised = promisify(jwt.verify.bind(jwt));
 
export enum AttributeKeys {
  Sub = 'sub',
  Email = 'email',
  PhoneNumber = 'phone_number',
  Website = 'website',
  CustomRoleId = 'custom:role_id',
  CustomCompanyId = 'custom:company_id',
  CustomCompanyIdentifier = 'custom:company_identifier',
  CustomUserStatus = 'custom:user_status',
  CustomUserName = 'custom:username',
  CustomCompanyStatus = 'custom:company_status',
  CustomCompanyName = 'custom:company_name',
  EmailVerified = 'email_verified',
  PhoneNumberVerified = 'phone_number_verified',
  Language = 'custom:language',
}
 
export interface Claim {
  sub: string;
  token_use: string;
  auth_time: number;
  iss: string;
  exp: number;
  username: string;
  scope: string;
  client_id: string;
  reason?: string;
  email: string;
}
 
export interface UserProfile extends RedirectRoute {
  id: number;
  identifier: string;
  name: string;
  avatar?: string;
  contact_email: string;
  contact_number: string;
  email: string;
  status: number;
  company_status: number;
  role_id: number;
  company_id: number;
  company_identifier: string;
  company_name: string;
  timezone: string;
  company_personas: Array<{
    company_id: number;
    persona_id: number;
  }>;
  is_admin?: boolean;
  settings?: Partial<UserSetting>;
 
  [key: string]: any;
}
 
interface TokenHeader {
  kid: string;
  alg: string;
}
 
interface PublicKey {
  alg: string;
  e: string;
  kid: string;
  kty: string;
  n: string;
  use: string;
}
 
interface PublicKeyMeta {
  instance: PublicKey;
  pem: string;
}
 
interface MapOfKidToPublicKey {
  [key: string]: PublicKeyMeta;
}
 
// Define version for aws
AWS.config.apiVersions = {
  cognitoidentityserviceprovider: AwsConfigs.cognitoConfig.version,
};
 
/**
 * Cache public keys from aws.
 */
let cacheKeys: MapOfKidToPublicKey | undefined;
 
/**
 * AWS Cognito Service
 */
export class AwsCognitoService {
  @inject(AwsServiceBindings.SES_SERVICE)
  public ses_service: AwsSesService;
 
  constructor() {}
 
  private throwTokenError(message: string): never {
    throw new HttpErrors.Unauthorized(`Error verifying token : ${message}`);
  }
 
  /**
   * Verify JWT token
   * @param The token
   * @returns Promise<Claim>
   */
  async verifyToken(token: string, options: AuthenticationStrategyOptions): Promise<Claim> {
    const {cognitoConfig} = AwsConfigs;
    if (!token) {
      this.throwTokenError('token is null');
    }
 
    const decoded = this.decodeToken(token);
    const keys = await this.getPublicKeys();
 
    this.validateKey(keys, decoded.header);
    if (!keys) {
      this.throwTokenError('Public keys are not available');
    }
    const claim = await this.getClaim(token, keys, decoded.header);
    this.validateClaim(claim, options, cognitoConfig);
 
    return claim;
  }
 
  private decodeToken(token: string): {header: TokenHeader} {
    const decoded = jwt.decode(token, {complete: true});
    if (!decoded || !decoded.header) {
      throw new Error('Token decoding failed');
    }
    return decoded;
  }
 
  private async getClaim(token: string, keys: MapOfKidToPublicKey, header: TokenHeader): Promise<Claim> {
    const key = keys[header.kid];
    return (await verifyPromised(token, key.pem)) as Claim;
  }
 
  private validateKey(keys: MapOfKidToPublicKey | undefined, header: TokenHeader): void {
    if (!keys?.[header.kid]) {
      throw new Error('claim made for unknown kid');
    }
  }
 
  private validateClaim(claim: Claim, options: AuthenticationStrategyOptions, cognitoConfig: any): void {
    const currentSeconds = Math.floor(new Date().valueOf() / 1000);
    if (currentSeconds > claim.exp || currentSeconds < claim.auth_time) {
      throw new Error('claim is expired or invalid');
    }
 
    if (claim.iss !== cognitoConfig.cognitoIssuer) {
      throw new Error('claim issuer is invalid');
    }
 
    if (claim.token_use !== options.token_use) {
      throw new Error(`claim use is not ${options.token_use}`);
    }
  }
 
  /**
   * Get public keys
   * @returns Promise<MapOfKidToPublicKey | undefined>
   */
  async getPublicKeys(): Promise<MapOfKidToPublicKey | undefined> {
    if (!cacheKeys) {
      const {cognitoConfig} = AwsConfigs;
      const url = `${cognitoConfig.cognitoIssuer}/.well-known/jwks.json`;
      const response = await fetch(url);
      const publicKeys = await response.json();
      cacheKeys = publicKeys.keys.reduce((agg: MapOfKidToPublicKey, current: PublicKey) => {
        const pem = jwkToPem(current);
        agg[current.kid] = {instance: current, pem};
        return agg;
      }, {} as MapOfKidToPublicKey);
      return cacheKeys;
    } else {
      return cacheKeys;
    }
  }
 
  /**
   * Create new user in cognito
   * @param user The user instance
   */
  async createUser(user: User): Promise<AdminCreateUserResponse> {
    const {cognitoConfig} = AwsConfigs;
    const cognitoProvider = new AWS.CognitoIdentityServiceProvider();
 
    const attributeList = this._buildAttributeListCognito(user);
 
    const cognitoUser: AdminCreateUserRequest = {
      Username: user.contact_email,
      UserPoolId: cognitoConfig.userPoolId,
      UserAttributes: attributeList,
      DesiredDeliveryMediums: ['EMAIL'],
    };
 
    return cognitoProvider.adminCreateUser(cognitoUser).promise();
  }
 
  /**
   * Update user information.
   * @param username The username.
   * @param user The user information.
   */
  async updateUser(username: string, user: AnyObject): Promise<AdminUpdateUserAttributesResponse> {
    const {cognitoConfig} = AwsConfigs;
    const cognitoProvider = new AWS.CognitoIdentityServiceProvider();
 
    const attributeList = this._buildAttributeListCognito(user);
 
    const cognitoUser: AdminUpdateUserAttributesRequest = {
      Username: username,
      UserPoolId: cognitoConfig.userPoolId,
      UserAttributes: attributeList,
    };
 
    try {
      if (user.contact_number && user.contact_number_overwrite) {
        await this.handleDuplicatedPhoneNumber(username, user, cognitoProvider);
      }
 
      return await cognitoProvider.adminUpdateUserAttributes(cognitoUser).promise();
    } catch (error) {
      console.log(error);
      return false;
    }
  }
 
  private async handleDuplicatedPhoneNumber(
    username: string,
    user: AnyObject,
    cognitoProvider: AWS.CognitoIdentityServiceProvider,
  ): Promise<void> {
    const {cognitoConfig} = AwsConfigs;
    const params: ListUsersRequest = {
      UserPoolId: cognitoConfig.userPoolId,
      AttributesToGet: [AttributeKeys.Email, AttributeKeys.PhoneNumber, AttributeKeys.CustomUserName],
      Filter: `phone_number ^= \"${user.contact_number}\"`,
      Limit: 60,
    };
    const duplicatedPhoneUserResult = await cognitoProvider.listUsers(params).promise();
    const successUpdatedOnCogito = duplicatedPhoneUserResult.Users?.filter(result => result.Username === username);
 
    if (duplicatedPhoneUserResult.Users?.length && successUpdatedOnCogito?.length) {
      const actions = duplicatedPhoneUserResult.Users.map(async duplicatedPhoneUser => {
        if (duplicatedPhoneUser.Username !== username) {
          await this.updateDuplicatedPhoneUser(duplicatedPhoneUser, user, cognitoProvider);
        }
      });
 
      await Promise.all(actions);
    }
  }
 
  private async updateDuplicatedPhoneUser(
    duplicatedPhoneUser: AWS.CognitoIdentityServiceProvider.UserType,
    user: AnyObject,
    cognitoProvider: AWS.CognitoIdentityServiceProvider,
  ): Promise<void> {
    const {cognitoConfig} = AwsConfigs;
    const duplicatedPhoneAttributeList = this._buildAttributeListCognito({
      contact_number: Constants.fakePhoneNumber, // Fake number
    });
    duplicatedPhoneAttributeList.push({
      Name: AttributeKeys.PhoneNumberVerified,
      Value: 'false',
    });
 
    const duplicatedPhoneCognitoUser: AdminUpdateUserAttributesRequest = {
      Username: duplicatedPhoneUser.Username ?? '',
      UserPoolId: cognitoConfig.userPoolId,
      UserAttributes: duplicatedPhoneAttributeList,
    };
 
    await cognitoProvider.adminUpdateUserAttributes(duplicatedPhoneCognitoUser).promise();
 
    const userAttribute: AnyObject = {};
    duplicatedPhoneUser.Attributes?.forEach(attribute => {
      userAttribute[attribute.Name] = attribute.Value;
    });
 
    const recipient = userAttribute[AttributeKeys.Email] ?? 'sang.ngo@dirox.net';
    const duplicatedPhoneUsername = userAttribute[AttributeKeys.CustomUserName] ?? 'Sang Ngo';
 
    await this.ses_service.sendTemplatedEmail(
      Constants.Email.InformUserAfterUpdateDuplicatedPhoneNumber,
      [{contact_email: recipient, language: user?.language ?? 'en'} as User],
      {
        username: duplicatedPhoneUsername,
        phone_number: user.contact_number,
      },
    );
  }
 
  /**
   * Disable an user in cognito.
   * @param username The username.
   */
  async disableUser(username: string): Promise<AdminUpdateUserAttributesResponse> {
    const {cognitoConfig} = AwsConfigs;
    const cognitoProvider = new AWS.CognitoIdentityServiceProvider();
 
    const params: AdminDisableUserRequest = {
      Username: username,
      UserPoolId: cognitoConfig.userPoolId,
    };
 
    return new Promise((resolve, reject) => {
      cognitoProvider.adminDisableUser(params, (err, data) => {
        if (err) {
          return reject(err);
        }
 
        return resolve(data);
      });
    });
  }
 
  /**
   * Update user information.
   * @param username The username.
   * @param user The user information.
   */
  async enableUser(username: string): Promise<AdminUpdateUserAttributesResponse> {
    const {cognitoConfig} = AwsConfigs;
    const cognitoProvider = new AWS.CognitoIdentityServiceProvider();
 
    const params: AdminEnableUserRequest = {
      Username: username,
      UserPoolId: cognitoConfig.userPoolId,
    };
 
    return new Promise((resolve, reject) => {
      cognitoProvider.adminEnableUser(params, (err, data) => {
        if (err) {
          return reject(err);
        }
 
        return resolve(data);
      });
    });
  }
 
  /**
   * Delete user in cognito.
   * @param username The username.
   */
  async deleteUser(username: string): Promise<{}> {
    const {cognitoConfig} = AwsConfigs;
    const cognitoProvider = new AWS.CognitoIdentityServiceProvider();
    const cognitoUser: AdminDeleteUserRequest = {
      Username: username,
      UserPoolId: cognitoConfig.userPoolId,
    };
 
    return new Promise((resolve, reject) => {
      cognitoProvider.adminDeleteUser(cognitoUser, (err, data) => {
        if (err) {
          return reject(err);
        }
 
        return resolve(data);
      });
    });
  }
 
  /**
   * Delete users in cognito.
   * @param username The username.
   */
  async deleteUsers(usernames: string[]): Promise<{}> {
    const pTasks: Promise<{}>[] = [];
    usernames.forEach((username, idx) => {
      pTasks[idx] = this.deleteUser(username);
    });
 
    return Promise.allSettled(pTasks);
  }
 
  /**
   * Builds attribute list cognito
   * @param user
   * @returns AttributeListType[]
   */
  private _buildAttributeListCognito(user: Partial<User>) {
    const attributeList: AttributeListType = [];
 
    this._buildAttributeListCognitoBase(user, attributeList);
    this._buildAttributeListCognitoRole(user, attributeList);
    this._buildAttributeListCognitoCompany(user, attributeList);
    this._buildAttributeListCognitoStatus(user, attributeList);
    this._buildAttributeListCognitoName(user, attributeList);
    this._buildAttributeListCognitoLanguage(user, attributeList);
 
    return attributeList;
  }
 
  /**
   * Build base attribute list
   * @param user The user information
   * @param attributeList The array of attributes
   */
  private _buildAttributeListCognitoBase(user: Partial<User>, attributeList: AttributeListType): void {
    if (user.contact_email) {
      attributeList.push({
        Name: AttributeKeys.Email,
        Value: user.contact_email,
      });
      attributeList.push({
        Name: AttributeKeys.EmailVerified,
        Value: 'true',
      });
    }
 
    if (user.contact_number) {
      attributeList.push({
        Name: AttributeKeys.PhoneNumber,
        Value: user.contact_number,
      });
    }
  }
 
  /**
   * Build role attribute list
   * @param user The user information
   * @param attributeList The array of attributes
   */
  private _buildAttributeListCognitoRole(user: Partial<User>, attributeList: AttributeListType): void {
    if (user.role_id) {
      attributeList.push({
        Name: AttributeKeys.CustomRoleId,
        Value: user.role_id.toString(),
      });
    }
  }
 
  /**
   * Build company attribute list
   * @param user The user information
   * @param attributeList The array of attributes
   */
  private _buildAttributeListCognitoCompany(user: Partial<User>, attributeList: AttributeListType): void {
    if (user.company_id) {
      attributeList.push({
        Name: AttributeKeys.CustomCompanyId,
        Value: user.company_id.toString(),
      });
    }
 
    if (user.company_identifier) {
      attributeList.push({
        Name: AttributeKeys.CustomCompanyIdentifier,
        Value: user.company_identifier,
      });
    }
 
    if (user.company_name) {
      // add company_name
      attributeList.push({
        Name: AttributeKeys.CustomCompanyName,
        Value: user.company_name,
      });
    }
  }
 
  /**
   * Build status attribute list
   * @param user The user information
   * @param attributeList The array of attributes
   */
  private _buildAttributeListCognitoStatus(user: Partial<User>, attributeList: AttributeListType): void {
    if (user.status) {
      attributeList.push({
        Name: AttributeKeys.CustomUserStatus,
        Value: user.status.toString(),
      });
    }
  }
 
  /**
   * Build name attribute list
   * @param user The user information
   * @param attributeList The array of attributes
   */
  private _buildAttributeListCognitoName(user: Partial<User>, attributeList: AttributeListType): void {
    if (user.name) {
      attributeList.push({
        Name: AttributeKeys.CustomUserName,
        Value: user.name,
      });
    }
  }
 
  /**
   * Build language attribute list
   * @param user The user information
   * @param attributeList The array of attributes
   */
  private _buildAttributeListCognitoLanguage(user: Partial<User>, attributeList: AttributeListType): void {
    if (user.language) {
      attributeList.push({
        Name: AttributeKeys.Language,
        Value: user.language,
      });
    }
  }
 
  /**
   * Retrieve value from name
   * @param name The name of attribute
   */
  public retrieveAttributeByName(name: string, attributes?: AttributeListType): AttributeType | undefined {
    if (!attributes) {
      return undefined;
    }
 
    return attributes.find(attribute => {
      return attribute.Name === name;
    });
  }
 
  /**
   * Get all users
   * @param user
   * @returns ListUsersResponse
   */
  public async getAllUsers() {
    const {cognitoConfig} = AwsConfigs;
    const cognitoProvider = new AWS.CognitoIdentityServiceProvider();
 
    const params: ListUsersRequest = {
      UserPoolId: cognitoConfig.userPoolId,
      Filter: 'cognito:user_status = "CONFIRMED"',
    };
 
    let users: AnyObject[] = [];
    let resUsers: ListUsersResponse;
 
    do {
      resUsers = await cognitoProvider.listUsers(params).promise();
      if (resUsers.Users) {
        users = users.concat(resUsers.Users);
      }
      params.PaginationToken = resUsers.PaginationToken;
    } while (resUsers.PaginationToken);
 
    return users;
  }
 
  async getUserInfo(accessToken: string): Promise<any> {
    const {cognitoConfig} = AwsConfigs;
 
    const url = `${cognitoConfig.domain}/oauth2/userInfo`;
 
    const res = await fetch(url, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
 
    if (!res.ok) {
      throw new Error(`Failed userInfo: ${res.status}`);
    }
 
    return res.json();
  }
 
  /**
   * Resends a temporary password to a user.
   *
   * @param {string} sub - The sub of the user to resend the temporary password to.
   * @return {Promise<void>} - A promise that resolves once the temporary password has been resent successfully.
   */
  public async resendTemporaryPassword(user: User): Promise<void> {
    const {cognitoConfig} = AwsConfigs;
    const cognitoProvider = new AWS.CognitoIdentityServiceProvider();
 
    const cognitoUser: AdminCreateUserRequest = {
      Username: user.contact_email,
      UserPoolId: cognitoConfig.userPoolId,
      DesiredDeliveryMediums: ['EMAIL'],
      MessageAction: 'RESEND',
    };
 
    await cognitoProvider.adminCreateUser(cognitoUser).promise();
  }
 
  public async forceVerifyAndResetPassword(username: string): Promise<void> {
    const {cognitoConfig} = AwsConfigs;
 
    const cognitoProvider = new AWS.CognitoIdentityServiceProvider();
 
    await cognitoProvider
      .adminUpdateUserAttributes({
        UserPoolId: cognitoConfig.userPoolId,
        Username: username,
        UserAttributes: [
          {
            Name: 'email_verified',
            Value: 'true',
          },
        ],
      })
      .promise();
 
    await cognitoProvider
      .adminResetUserPassword({
        UserPoolId: cognitoConfig.userPoolId,
        Username: username,
      })
      .promise();
  }
}