all files / firebase/modules/auth/ PhoneAuthListener.js

0% Statements 0/78
0% Branches 0/32
0% Functions 0/21
0% Lines 0/74
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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
// @flow
import INTERNALS from '../../utils/internals';
import { SharedEventEmitter } from '../../utils/events';
import {
  generatePushID,
  isFunction,
  isAndroid,
  isIOS,
  isString,
  nativeToJSError,
} from '../../utils';
import { getNativeModule } from '../../utils/native';
 
import type Auth from './';
 
type PhoneAuthSnapshot = {
  state: 'sent' | 'timeout' | 'verified' | 'error',
  verificationId: string,
  code: string | null,
  error: Error | null,
};
 
type PhoneAuthError = {
  code: string | null,
  verificationId: string,
  message: string | null,
  stack: string | null,
};
 
export default class PhoneAuthListener {
  _auth: Auth;
  _timeout: number;
  _publicEvents: Object;
  _internalEvents: Object;
  _reject: Function | null;
  _resolve: Function | null;
  _credential: Object | null;
  _promise: Promise<*> | null;
  _phoneAuthRequestKey: string;
 
  /**
   *
   * @param auth
   * @param phoneNumber
   * @param timeout
   */
  constructor(auth: Auth, phoneNumber: string, timeout?: number) {
    this._auth = auth;
    this._reject = null;
    this._resolve = null;
    this._promise = null;
    this._credential = null;
 
    this._timeout = timeout || 20; // 20 secs
    this._phoneAuthRequestKey = generatePushID();
 
    // internal events
    this._internalEvents = {
      codeSent: `phone:auth:${this._phoneAuthRequestKey}:onCodeSent`,
      verificationFailed: `phone:auth:${
        this._phoneAuthRequestKey
      }:onVerificationFailed`,
      verificationComplete: `phone:auth:${
        this._phoneAuthRequestKey
      }:onVerificationComplete`,
      codeAutoRetrievalTimeout: `phone:auth:${
        this._phoneAuthRequestKey
      }:onCodeAutoRetrievalTimeout`,
    };
 
    // user observer events
    this._publicEvents = {
      // error cb
      error: `phone:auth:${this._phoneAuthRequestKey}:error`,
      // observer
      event: `phone:auth:${this._phoneAuthRequestKey}:event`,
      // success cb
      success: `phone:auth:${this._phoneAuthRequestKey}:success`,
    };
 
    // setup internal event listeners
    this._subscribeToEvents();
 
    // start verification flow natively
    if (isAndroid) {
      getNativeModule(this._auth).verifyPhoneNumber(
        phoneNumber,
        this._phoneAuthRequestKey,
        this._timeout
      );
    }
 
    if (isIOS) {
      getNativeModule(this._auth).verifyPhoneNumber(
        phoneNumber,
        this._phoneAuthRequestKey
      );
    }
  }
 
  /**
   * Subscribes to all EE events on this._internalEvents
   * @private
   */
  _subscribeToEvents() {
    const events = Object.keys(this._internalEvents);
 
    for (let i = 0, len = events.length; i < len; i++) {
      const type = events[i];
      SharedEventEmitter.once(
        this._internalEvents[type],
        // $FlowExpectedError: Flow doesn't support indexable signatures on classes: https://github.com/facebook/flow/issues/1323
        this[`_${type}Handler`].bind(this)
      );
    }
  }
 
  /**
   * Subscribe a users listener cb to the snapshot events.
   * @param observer
   * @private
   */
  _addUserObserver(observer) {
    SharedEventEmitter.addListener(this._publicEvents.event, observer);
  }
 
  /**
   * Send a snapshot event to users event observer.
   * @param snapshot PhoneAuthSnapshot
   * @private
   */
  _emitToObservers(snapshot: PhoneAuthSnapshot) {
    SharedEventEmitter.emit(this._publicEvents.event, snapshot);
  }
 
  /**
   * Send a error snapshot event to any subscribed errorCb's
   * @param snapshot
   * @private
   */
  _emitToErrorCb(snapshot) {
    const { error } = snapshot;
    if (this._reject) this._reject(error);
    SharedEventEmitter.emit(this._publicEvents.error, error);
  }
 
  /**
   * Send a success snapshot event to any subscribed completeCb's
   * @param snapshot
   * @private
   */
  _emitToSuccessCb(snapshot) {
    if (this._resolve) this._resolve(snapshot);
    SharedEventEmitter.emit(this._publicEvents.success, snapshot);
  }
 
  /**
   * Removes all listeners for this phone auth instance
   * @private
   */
  _removeAllListeners() {
    setTimeout(() => {
      // move to next event loop - not sure if needed
      // internal listeners
      Object.values(this._internalEvents).forEach(event => {
        SharedEventEmitter.removeAllListeners(event);
      });
 
      // user observer listeners
      Object.values(this._publicEvents).forEach(publicEvent => {
        SharedEventEmitter.removeAllListeners(publicEvent);
      });
    }, 0);
  }
 
  /**
   * Create a new internal deferred promise, if not already created
   * @private
   */
  _promiseDeferred() {
    if (!this._promise) {
      this._promise = new Promise((resolve, reject) => {
        this._resolve = result => {
          this._resolve = null;
          return resolve(result);
        };
 
        this._reject = possibleError => {
          this._reject = null;
          return reject(possibleError);
        };
      });
    }
  }
 
  /* --------------------------
   --- INTERNAL EVENT HANDLERS
   ---------------------------- */
 
  /**
   * Internal code sent event handler
   * @private
   * @param credential
   */
  _codeSentHandler(credential) {
    const snapshot: PhoneAuthSnapshot = {
      verificationId: credential.verificationId,
      code: null,
      error: null,
      state: 'sent',
    };
 
    this._emitToObservers(snapshot);
 
    if (isIOS) {
      this._emitToSuccessCb(snapshot);
    }
 
    if (isAndroid) {
      // android can auto retrieve so we don't emit to successCb immediately,
      // if auto retrieve times out then that will emit to successCb
    }
  }
 
  /**
   * Internal code auto retrieve timeout event handler
   * @private
   * @param credential
   */
  _codeAutoRetrievalTimeoutHandler(credential) {
    const snapshot: PhoneAuthSnapshot = {
      verificationId: credential.verificationId,
      code: null,
      error: null,
      state: 'timeout',
    };
 
    this._emitToObservers(snapshot);
    this._emitToSuccessCb(snapshot);
  }
 
  /**
   * Internal verification complete event handler
   * @param credential
   * @private
   */
  _verificationCompleteHandler(credential) {
    const snapshot: PhoneAuthSnapshot = {
      verificationId: credential.verificationId,
      code: credential.code || null,
      error: null,
      state: 'verified',
    };
 
    this._emitToObservers(snapshot);
    this._emitToSuccessCb(snapshot);
    this._removeAllListeners();
  }
 
  /**
   * Internal verification failed event handler
   * @param state
   * @private
   */
  _verificationFailedHandler(state) {
    const snapshot: PhoneAuthSnapshot = {
      verificationId: state.verificationId,
      code: null,
      error: null,
      state: 'error',
    };
 
    const { code, message, nativeErrorMessage } = state.error;
    snapshot.error = nativeToJSError(code, message, { nativeErrorMessage });
 
    this._emitToObservers(snapshot);
    this._emitToErrorCb(snapshot);
    this._removeAllListeners();
  }
 
  /* -------------
   -- PUBLIC API
   --------------*/
 
  on(
    event: string,
    observer: () => PhoneAuthSnapshot,
    errorCb?: () => PhoneAuthError,
    successCb?: () => PhoneAuthSnapshot
  ): this {
    if (!isString(event)) {
      throw new Error(
        INTERNALS.STRINGS.ERROR_MISSING_ARG_NAMED('event', 'string', 'on')
      );
    }
 
    if (event !== 'state_changed') {
      throw new Error(
        INTERNALS.STRINGS.ERROR_ARG_INVALID_VALUE(
          'event',
          'state_changed',
          event
        )
      );
    }
 
    if (!isFunction(observer)) {
      throw new Error(
        INTERNALS.STRINGS.ERROR_MISSING_ARG_NAMED('observer', 'function', 'on')
      );
    }
 
    this._addUserObserver(observer);
 
    if (isFunction(errorCb)) {
      SharedEventEmitter.once(this._publicEvents.error, errorCb);
    }
 
    if (isFunction(successCb)) {
      SharedEventEmitter.once(this._publicEvents.success, successCb);
    }
 
    return this;
  }
 
  /**
   * Promise .then proxy
   * @param fn
   */
  then(fn: () => PhoneAuthSnapshot) {
    this._promiseDeferred();
    // $FlowFixMe: Unsure how to annotate `bind` here
    if (this._promise) return this._promise.then.bind(this._promise)(fn);
    return undefined; // will never get here - just to keep flow happy
  }
 
  /**
   * Promise .catch proxy
   * @param fn
   */
  catch(fn: () => Error) {
    this._promiseDeferred();
    // $FlowFixMe: Unsure how to annotate `bind` here
    if (this._promise) return this._promise.catch.bind(this._promise)(fn);
    return undefined; // will never get here - just to keep flow happy
  }
}