All files / src/authzero auth0Service.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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 22011x 11x 11x                 11x 11x     11x 54x   54x     54x 54x 54x 54x         5x           5x             1x         3x 3x 3x 3x       3x               3x 3x 1x   2x 2x     2x 2x                 4x 4x     4x                     4x 3x 3x   1x   4x               4x 4x 2x 2x             2x 2x     2x 2x           2x         2x         2x   2x       2x 2x 2x 2x 1x   1x 1x           2x           2x     2x           2x 2x 1x   1x 1x           2x 2x   2x 2x         1x       1x 1x         2x       2x           2x          
import { Injectable, HttpService } from '@nestjs/common';
import { EnvironmentService } from '../common_services/config/envService';
import {
  IdentitySignUpInputDto,
  ChangePasswordInputDto,
  IdentityLoginInputDto,
  IdentityDto,
  CheckAccessTokenInputDto,
  PhoneRegistrationDto,
} from '../identity/dtos/identityDto';
 
import { SmsService } from './smsService';
import JwtValidator from './utils/jwt/jwtValidator';
 
@Injectable()
export class Auth0Service {
  contentType = 'application/json';
 
  auth0ConnectionType = 'Username-Password-Authentication';
 
  constructor(
    private readonly envService: EnvironmentService,
    private readonly http: HttpService,
    private readonly smsService: SmsService,
    private readonly jwtValidator: JwtValidator,
  ) {}
 
  /* Get Management API token */
  private getAdminToken() {
    const options = {
      client_id: this.envService.auth0ClientKey,
      client_secret: this.envService.auth0ClientSecret,
      audience: this.envService.auth0ManagementAudience,
      grant_type: 'client_credentials',
    };
    return this.http
      .post(this.envService.auth0UrlGetToken, options)
      .toPromise();
  }
 
  /* checkAccessToken functions */
  public checkAccessToken(input: CheckAccessTokenInputDto) {
    return this.jwtValidator.validate(input.accessToken);
  }
 
  /* identitySignUp */
  public async createUser(input: IdentitySignUpInputDto): Promise<boolean> {
    try {
      const adminTokenResponse = await this.getAdminToken();
      const adminToken = adminTokenResponse.data.access_token;
      const headers = {
        'Content-Type': this.contentType,
        authorization: `Bearer ${adminToken}`,
      };
      const options = {
        email: input.email,
        password: input.password,
        connection: this.auth0ConnectionType,
        user_metadata: {
          deviceUuid: input.deviceUuid,
        },
      };
      const url = this.envService.auth0UrlCreateUser;
      await this.http.post(url, options, { headers }).toPromise();
      return Promise.resolve(true);
    } catch (e) {
      console.error(e);
      const errorMessage = e.response
        ? `${e.message}. Reason:${e.response.data.message}`
        : e.message;
      const error = new Error(errorMessage);
      return Promise.reject(error);
    }
  }
 
  /* identityLogin functions */
  private getUserToken(
    input: IdentityLoginInputDto | CheckAccessTokenInputDto,
  ) {
    // Get accessToken with a password or a refresh_token
    const grantType = input.refreshToken ? 'refresh_token' : 'password';
    const headers = {
      'Content-Type': this.contentType,
    };
    const options = {
      grant_type: grantType,
      username: '',
      password: '',
      refresh_token: '',
      scope: 'offline_access openid profile email',
      audience: this.envService.auth0Audience,
      client_id: this.envService.auth0ClientKey,
      client_secret: this.envService.auth0ClientSecret,
    };
 
    if (grantType === 'password') {
      options.username = (input as IdentityLoginInputDto).email;
      options.password = (input as IdentityLoginInputDto).password;
    } else {
      options.refresh_token = (input as CheckAccessTokenInputDto).refreshToken;
    }
    return this.http.post(this.envService.auth0UrlGetToken, options, {
      headers,
    });
  }
 
  async getIdentity(
    input: IdentityLoginInputDto | CheckAccessTokenInputDto,
  ): Promise<IdentityDto> {
    try {
      const userTokens = await this.getUserToken(input).toPromise();
      const responseData = userTokens.data;
      return new IdentityDto(
        true,
        responseData.access_token,
        responseData.refresh_token,
        responseData.id_token,
      );
    } catch (e) {
      console.error(e);
      const errorMessage = e.response
        ? `${e.message}. Reason:${e.response.data.error_description}`
        : e.message;
      const error = new Error(errorMessage);
      return Promise.reject(error);
    }
  }
 
  /* identityChangePassword functions */
  private setNewPassword(input: ChangePasswordInputDto, adminToken: string) {
    const headers = {
      'Content-Type': this.contentType,
      authorization: `Bearer ${adminToken}`,
    };
 
    const options = {
      password: input.password,
      connection: this.auth0ConnectionType,
    };
 
    const url = `${this.envService.auth0UrlChangePwd}${input.userId}`;
 
    return this.http.patch(url, options, { headers }).toPromise();
  }
 
  public async changePassword(input: ChangePasswordInputDto) {
    try {
      const adminTokenResponse = await this.getAdminToken();
      const adminToken = adminTokenResponse.data.access_token;
      await this.setNewPassword(input, adminToken);
      return true;
    } catch (e) {
      console.error(e);
      return false;
    }
  }
 
  /* identityForgotPassword functions */
  private triggerForgotPasswordFlow(email: string) {
    const options = {
      email,
      connection: this.auth0ConnectionType,
      client_id: this.envService.auth0ClientKey,
    };
 
    const headers = {
      'Content-Type': this.contentType,
    };
    return this.http.post(this.envService.auth0UrlForgotPwd, options, {
      headers,
    });
  }
 
  public async forgotPassword(email: string): Promise<boolean> {
    try {
      await this.triggerForgotPasswordFlow(email).toPromise();
      return true;
    } catch (e) {
      console.error(e);
      return false;
    }
  }
 
  public async phoneRegister(phone: string) {
    // TODO: implement me -- generate code, get senderId and message pattern from env ?
    const verificationCode = 'Your verification code: 10240';
    const senderId = 'Zeller'; // must be 1-11 alpha-numeric characters
    //
    try {
      await this.smsService.sendSMS(
        phone,
        JSON.stringify(verificationCode),
        senderId,
      );
      return Promise.resolve(
        new PhoneRegistrationDto(true, new Date().toISOString()),
      );
    } catch (e) {
      console.error(e);
      return Promise.reject(e);
    }
  }
 
  async revokeRefreshToken(refreshToken: string) {
    const headers = {
      'Content-Type': this.contentType,
    };
 
    const options = {
      token: refreshToken,
      client_id: this.envService.auth0ClientKey,
      client_secret: this.envService.auth0ClientSecret,
    };
 
    return this.http.post(this.envService.auth0UrlRevokeToken, options, {
      headers,
    });
  }
}