All files / src/identity/service identityService.ts

100% Statements 74/74
100% Branches 8/8
100% Functions 12/12
100% Lines 72/72

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 2028x 8x   8x 8x 8x                 8x 8x 8x     8x   24x 24x 24x 24x           2x 2x   1x         1x   1x           1x   1x   1x 1x         2x 2x   1x         1x 1x   1x 1x             6x 6x   6x     1x   5x     5x   5x           5x 1x     4x   1x         2x 1x 1x         1x     1x     2x 2x         2x           2x           2x 1x         1x 1x       2x 2x 1x   1x   1x         2x             2x 2x 2x 1x 1x 1x 1x     1x 1x         1x                 1x               1x 1x      
import { Injectable } from '@nestjs/common';
import gql from 'graphql-tag';
import { PinInput, PhoneRegisterInput, PhoneVerifyInput, DeviceStatus } from '../../types.d';
import { DeviceVerification } from '../../devices/deviceVerification';
import { DeviceService } from '../../devices/deviceService';
import {
  IdentitySignUpInputDto,
  IdentityLoginInputDto,
  CheckAccessTokenInputDto,
  ChangePasswordInputDto,
  IdentityDto,
  PhoneRegistrationDto,
  PhoneVerificationDto,
} from '../dtos/identityDto';
import { Auth0Service } from '../../authzero/auth0Service';
import { JWT_CHECK_RESULT } from '../../authzero/utils/jwt/jwtValidator';
import { AppSyncClient } from '../../common_services/appsync';
 
@Injectable()
export class IdentityService {
  constructor(
    private readonly auth0Service: Auth0Service,
    private readonly deviceService: DeviceService,
    private readonly deviceVerification: DeviceVerification,
    private readonly appSyncClient: AppSyncClient,
  ) {}
 
  async identitySignUp(
    signUpInput: IdentitySignUpInputDto,
  ): Promise<IdentityDto> {
    try {
      await this.auth0Service.createUser(signUpInput);
 
      const loginInput = new IdentityLoginInputDto(
        signUpInput.email,
        signUpInput.password,
        '',
      );
      const identity = await this.auth0Service.getIdentity(loginInput);
 
      await this.deviceService.saveDeviceTokens(
        signUpInput.deviceUuid,
        identity.accessToken,
        identity.refreshToken,
      );
 
      await this.deviceService.saveDeviceStatus(signUpInput.deviceUuid, DeviceStatus.ACTIVE);
 
      return Promise.resolve(identity);
    } catch (e) {
      console.error(e.message);
      return Promise.reject(e);
    }
  }
 
  async identityLogin(loginInput: IdentityLoginInputDto): Promise<IdentityDto> {
    try {
      const identity = await this.auth0Service.getIdentity(loginInput);
 
      await this.deviceService.saveDeviceTokens(
        loginInput.deviceUuid,
        identity.accessToken,
        identity.refreshToken,
      );
      await this.deviceService.saveDeviceStatus(loginInput.deviceUuid, DeviceStatus.ACTIVE);
      return Promise.resolve(identity);
    } catch (e) {
      console.error(e.message);
      return Promise.reject(e);
    }
  }
 
  async checkAccessToken(
    input: CheckAccessTokenInputDto,
  ): Promise<IdentityDto | undefined> {
    try {
      const jwtCheck = await this.auth0Service.checkAccessToken(input);
      // exit the function if it's a malformed or invalid accessToken
      switch (jwtCheck.code) {
        case JWT_CHECK_RESULT.ERROR_MALFORMED_TOKEN.code:
        case JWT_CHECK_RESULT.ERROR_UNHANDLED.code:
          return Promise.reject(new Error(jwtCheck.errorMessage));
        default:
          break;
      }
 
      console.info(jwtCheck);
 
      const validDeviceToken = await this.deviceVerification.isDeviceTokenValid(
        input.deviceUuid,
        input.accessToken,
        input.refreshToken,
      );
 
      if (!validDeviceToken) {
        return Promise.reject(new Error('DEVICE_TOKEN_INVALID'));
      }
 
      switch (jwtCheck.code) {
        case JWT_CHECK_RESULT.VALID_TOKEN.code: {
          return Promise.resolve(
            new IdentityDto(true, input.accessToken, input.refreshToken),
          );
        }
        case JWT_CHECK_RESULT.ERROR_TOKEN_EXPIRED.code: {
          const identity = await this.auth0Service.getIdentity(input);
          identity.refreshToken = input.refreshToken;
          await this.deviceService.saveDeviceTokens(
            input.deviceUuid,
            identity.accessToken,
            identity.refreshToken,
          );
          return Promise.resolve(identity);
        }
        default:
          throw new Error('Unhandled JWT ERROR');
      }
    } catch (e) {
      console.error(e);
      return Promise.reject(e);
    }
  }
 
  identityForgotPassword(email: string): Promise<boolean> {
    return this.auth0Service.forgotPassword(email);
  }
 
  identityChangePassword(
    changePwdInput: ChangePasswordInputDto,
  ): Promise<boolean> {
    return this.auth0Service.changePassword(changePwdInput);
  }
 
  async identityPhoneRegister(
    input: PhoneRegisterInput,
  ): Promise<PhoneRegistrationDto> {
    await this.deviceService.saveDevicePhone(input.deviceUuid, input.phone);
    return this.auth0Service.phoneRegister(input.phone);
  }
 
  identityPhoneVerify(input: PhoneVerifyInput): Promise<PhoneVerificationDto> {
    // TODO: implement me -- identityPhone verify logic
    console.log(input.code);
    return Promise.resolve(new PhoneVerificationDto(true));
  }
 
  async identitySetPin(input: PinInput): Promise<boolean | undefined> {
    try {
      await this.deviceService.saveDevicePin(input.deviceUuid, input.pin);
      return Promise.resolve(true);
    } catch (e) {
      console.error(e);
      /* eslint-disable */
      return Promise.reject(false);
    }
  }
 
  identityVerifyPin(input: PinInput): Promise<boolean | undefined> {
    return this.deviceVerification.isDevicePinValid(
      input.pin,
      input.deviceUuid
    );
  }
 
  async identityForcedLogoff(deviceUuid: string, reason: string) {
    console.log(`${deviceUuid}, ${reason}`)
    try {
    const refreshToken = await this.deviceService.getRefreshTokenByUuid(deviceUuid);
    await this.auth0Service.revokeRefreshToken(refreshToken)
    await this.deviceService.deactivateDevice(deviceUuid)
    console.info("identityForcedLogoff completed");
    return Promise.resolve({ deviceUuid: deviceUuid, reason: reason });
    }
    catch(e){
      console.error(`identityForcedLogoff falied. ${JSON.stringify(e)}`);
      return Promise.reject(new Error('An error happened during forced logoff'));
    }
  }
 
  async initiateForcedLogoff(deviceUuid: string, reason: string) {
    const mutation = gql`
      mutation TriggerLogoff($_deviceUuid: ID!, $_reason: String!) {
        identityForcedLogoff(deviceUuid: $_deviceUuid, reason: $_reason) {
          deviceUuid
          reason
        }
      }
    `;
 
    const request = {
      mutation,
      variables: {
        _deviceUuid: deviceUuid,
        _reason: reason,
      }
    };
 
    const client = await this.appSyncClient.getAppSyncClient();
    return client.mutate(request);
  }
}