GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

8505 lines
360 KiB

2 months ago
  1. 'use strict';
  2. var tslib = require('tslib');
  3. var util = require('@firebase/util');
  4. var app = require('@firebase/app');
  5. var component = require('@firebase/component');
  6. var logger = require('@firebase/logger');
  7. /**
  8. * @license
  9. * Copyright 2020 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. function _debugErrorMap() {
  24. var _a;
  25. return _a = {},
  26. _a["admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */] = 'This operation is restricted to administrators only.',
  27. _a["argument-error" /* AuthErrorCode.ARGUMENT_ERROR */] = '',
  28. _a["app-not-authorized" /* AuthErrorCode.APP_NOT_AUTHORIZED */] = "This app, identified by the domain where it's hosted, is not " +
  29. 'authorized to use Firebase Authentication with the provided API key. ' +
  30. 'Review your key configuration in the Google API console.',
  31. _a["app-not-installed" /* AuthErrorCode.APP_NOT_INSTALLED */] = 'The requested mobile application corresponding to the identifier (' +
  32. 'Android package name or iOS bundle ID) provided is not installed on ' +
  33. 'this device.',
  34. _a["captcha-check-failed" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */] = 'The reCAPTCHA response token provided is either invalid, expired, ' +
  35. 'already used or the domain associated with it does not match the list ' +
  36. 'of whitelisted domains.',
  37. _a["code-expired" /* AuthErrorCode.CODE_EXPIRED */] = 'The SMS code has expired. Please re-send the verification code to try ' +
  38. 'again.',
  39. _a["cordova-not-ready" /* AuthErrorCode.CORDOVA_NOT_READY */] = 'Cordova framework is not ready.',
  40. _a["cors-unsupported" /* AuthErrorCode.CORS_UNSUPPORTED */] = 'This browser is not supported.',
  41. _a["credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */] = 'This credential is already associated with a different user account.',
  42. _a["custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */] = 'The custom token corresponds to a different audience.',
  43. _a["requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = 'This operation is sensitive and requires recent authentication. Log in ' +
  44. 'again before retrying this request.',
  45. _a["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  46. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  47. 'starting any other Firebase SDK.',
  48. _a["dynamic-link-not-activated" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */] = 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
  49. 'conditions.',
  50. _a["email-change-needs-verification" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */] = 'Multi-factor users must always have a verified email.',
  51. _a["email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */] = 'The email address is already in use by another account.',
  52. _a["emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */] = 'Auth instance has already been used to make a network call. Auth can ' +
  53. 'no longer be configured to use the emulator. Try calling ' +
  54. '"connectAuthEmulator()" sooner.',
  55. _a["expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */] = 'The action code has expired.',
  56. _a["cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */] = 'This operation has been cancelled due to another conflicting popup being opened.',
  57. _a["internal-error" /* AuthErrorCode.INTERNAL_ERROR */] = 'An internal AuthError has occurred.',
  58. _a["invalid-app-credential" /* AuthErrorCode.INVALID_APP_CREDENTIAL */] = 'The phone verification request contains an invalid application verifier.' +
  59. ' The reCAPTCHA token response is either invalid or expired.',
  60. _a["invalid-app-id" /* AuthErrorCode.INVALID_APP_ID */] = 'The mobile app identifier is not registed for the current project.',
  61. _a["invalid-user-token" /* AuthErrorCode.INVALID_AUTH */] = "This user's credential isn't valid for this project. This can happen " +
  62. "if the user's token has been tampered with, or if the user isn't for " +
  63. 'the project associated with this API key.',
  64. _a["invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  65. _a["invalid-verification-code" /* AuthErrorCode.INVALID_CODE */] = 'The SMS verification code used to create the phone auth credential is ' +
  66. 'invalid. Please resend the verification code sms and be sure to use the ' +
  67. 'verification code provided by the user.',
  68. _a["invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */] = 'The continue URL provided in the request is invalid.',
  69. _a["invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */] = 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
  70. 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
  71. 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
  72. 'cordova-plugin-customurlscheme.',
  73. _a["invalid-custom-token" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */] = 'The custom token format is incorrect. Please check the documentation.',
  74. _a["invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */] = 'The provided dynamic link domain is not configured or authorized for the current project.',
  75. _a["invalid-email" /* AuthErrorCode.INVALID_EMAIL */] = 'The email address is badly formatted.',
  76. _a["invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */] = 'Emulator URL must start with a valid scheme (http:// or https://).',
  77. _a["invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */] = 'Your API key is invalid, please check you have copied it correctly.',
  78. _a["invalid-cert-hash" /* AuthErrorCode.INVALID_CERT_HASH */] = 'The SHA-1 certificate hash provided is invalid.',
  79. _a["invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */] = 'The supplied auth credential is malformed or has expired.',
  80. _a["invalid-message-payload" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */] = 'The email template corresponding to this action contains invalid characters in its message. ' +
  81. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  82. _a["invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */] = 'The request does not contain a valid proof of first factor successful sign-in.',
  83. _a["invalid-oauth-provider" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */] = 'EmailAuthProvider is not supported for this operation. This operation ' +
  84. 'only supports OAuth providers.',
  85. _a["invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */] = 'The OAuth client ID provided is either invalid or does not match the ' +
  86. 'specified API key.',
  87. _a["unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */] = 'This domain is not authorized for OAuth operations for your Firebase ' +
  88. 'project. Edit the list of authorized domains from the Firebase console.',
  89. _a["invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */] = 'The action code is invalid. This can happen if the code is malformed, ' +
  90. 'expired, or has already been used.',
  91. _a["wrong-password" /* AuthErrorCode.INVALID_PASSWORD */] = 'The password is invalid or the user does not have a password.',
  92. _a["invalid-persistence-type" /* AuthErrorCode.INVALID_PERSISTENCE */] = 'The specified persistence type is invalid. It can only be local, session or none.',
  93. _a["invalid-phone-number" /* AuthErrorCode.INVALID_PHONE_NUMBER */] = 'The format of the phone number provided is incorrect. Please enter the ' +
  94. 'phone number in a format that can be parsed into E.164 format. E.164 ' +
  95. 'phone numbers are written in the format [+][country code][subscriber ' +
  96. 'number including area code].',
  97. _a["invalid-provider-id" /* AuthErrorCode.INVALID_PROVIDER_ID */] = 'The specified provider ID is invalid.',
  98. _a["invalid-recipient-email" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */] = 'The email corresponding to this action failed to send as the provided ' +
  99. 'recipient email address is invalid.',
  100. _a["invalid-sender" /* AuthErrorCode.INVALID_SENDER */] = 'The email template corresponding to this action contains an invalid sender email or name. ' +
  101. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  102. _a["invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */] = 'The verification ID used to create the phone auth credential is invalid.',
  103. _a["invalid-tenant-id" /* AuthErrorCode.INVALID_TENANT_ID */] = "The Auth instance's tenant ID is invalid.",
  104. _a["login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */] = 'Login blocked by user-provided method: {$originalMessage}',
  105. _a["missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */] = 'An Android Package Name must be provided if the Android App is required to be installed.',
  106. _a["auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */] = 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
  107. 'by following the instructions in the Firebase console.',
  108. _a["missing-app-credential" /* AuthErrorCode.MISSING_APP_CREDENTIAL */] = 'The phone verification request is missing an application verifier ' +
  109. 'assertion. A reCAPTCHA response token needs to be provided.',
  110. _a["missing-verification-code" /* AuthErrorCode.MISSING_CODE */] = 'The phone auth credential was created with an empty SMS verification code.',
  111. _a["missing-continue-uri" /* AuthErrorCode.MISSING_CONTINUE_URI */] = 'A continue URL must be provided in the request.',
  112. _a["missing-iframe-start" /* AuthErrorCode.MISSING_IFRAME_START */] = 'An internal AuthError has occurred.',
  113. _a["missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */] = 'An iOS Bundle ID must be provided if an App Store ID is provided.',
  114. _a["missing-or-invalid-nonce" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */] = 'The request does not contain a valid nonce. This can occur if the ' +
  115. 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
  116. 'in the ID token payload.',
  117. _a["missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */] = 'No second factor identifier is provided.',
  118. _a["missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */] = 'The request is missing proof of first factor successful sign-in.',
  119. _a["missing-phone-number" /* AuthErrorCode.MISSING_PHONE_NUMBER */] = 'To send verification codes, provide a phone number for the recipient.',
  120. _a["missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */] = 'The phone auth credential was created with an empty verification ID.',
  121. _a["app-deleted" /* AuthErrorCode.MODULE_DESTROYED */] = 'This instance of FirebaseApp has been deleted.',
  122. _a["multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */] = 'The user does not have a second factor matching the identifier provided.',
  123. _a["multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */] = 'Proof of ownership of a second factor is required to complete sign-in.',
  124. _a["account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */] = 'An account already exists with the same email address but different ' +
  125. 'sign-in credentials. Sign in using a provider associated with this ' +
  126. 'email address.',
  127. _a["network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */] = 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
  128. _a["no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  129. _a["no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */] = 'User was not linked to an account with the given provider.',
  130. _a["null-user" /* AuthErrorCode.NULL_USER */] = 'A null user object was provided as the argument for an operation which ' +
  131. 'requires a non-null user object.',
  132. _a["operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */] = 'The given sign-in provider is disabled for this Firebase project. ' +
  133. 'Enable it in the Firebase console, under the sign-in method tab of the ' +
  134. 'Auth section.',
  135. _a["operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */] = 'This operation is not supported in the environment this application is ' +
  136. 'running on. "location.protocol" must be http, https or chrome-extension' +
  137. ' and web storage must be enabled.',
  138. _a["popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */] = 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
  139. _a["popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */] = 'The popup has been closed by the user before finalizing the operation.',
  140. _a["provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */] = 'User can only be linked to one identity for the given provider.',
  141. _a["quota-exceeded" /* AuthErrorCode.QUOTA_EXCEEDED */] = "The project's quota for this operation has been exceeded.",
  142. _a["redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */] = 'The redirect operation has been cancelled by the user before finalizing.',
  143. _a["redirect-operation-pending" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */] = 'A redirect sign-in operation is already pending.',
  144. _a["rejected-credential" /* AuthErrorCode.REJECTED_CREDENTIAL */] = 'The request contains malformed or mismatching credentials.',
  145. _a["second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */] = 'The second factor is already enrolled on this account.',
  146. _a["maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */] = 'The maximum allowed number of second factors on a user has been exceeded.',
  147. _a["tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */] = "The provided tenant ID does not match the Auth instance's tenant ID",
  148. _a["timeout" /* AuthErrorCode.TIMEOUT */] = 'The operation has timed out.',
  149. _a["user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */] = "The user's credential is no longer valid. The user must sign in again.",
  150. _a["too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */] = 'We have blocked all requests from this device due to unusual activity. ' +
  151. 'Try again later.',
  152. _a["unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */] = 'The domain of the continue URL is not whitelisted. Please whitelist ' +
  153. 'the domain in the Firebase console.',
  154. _a["unsupported-first-factor" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */] = 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',
  155. _a["unsupported-persistence-type" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */] = 'The current environment does not support the specified persistence type.',
  156. _a["unsupported-tenant-operation" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */] = 'This operation is not supported in a multi-tenant context.',
  157. _a["unverified-email" /* AuthErrorCode.UNVERIFIED_EMAIL */] = 'The operation requires a verified email.',
  158. _a["user-cancelled" /* AuthErrorCode.USER_CANCELLED */] = 'The user did not grant your application the permissions it requested.',
  159. _a["user-not-found" /* AuthErrorCode.USER_DELETED */] = 'There is no user record corresponding to this identifier. The user may ' +
  160. 'have been deleted.',
  161. _a["user-disabled" /* AuthErrorCode.USER_DISABLED */] = 'The user account has been disabled by an administrator.',
  162. _a["user-mismatch" /* AuthErrorCode.USER_MISMATCH */] = 'The supplied credentials do not correspond to the previously signed in user.',
  163. _a["user-signed-out" /* AuthErrorCode.USER_SIGNED_OUT */] = '',
  164. _a["weak-password" /* AuthErrorCode.WEAK_PASSWORD */] = 'The password must be 6 characters long or more.',
  165. _a["web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */] = 'This browser is not supported or 3rd party cookies and data may be disabled.',
  166. _a["already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */] = 'initializeAuth() has already been called with ' +
  167. 'different options. To avoid this error, call initializeAuth() with the ' +
  168. 'same options as when it was originally called, or call getAuth() to return the' +
  169. ' already initialized instance.',
  170. _a;
  171. }
  172. function _prodErrorMap() {
  173. var _a;
  174. // We will include this one message in the prod error map since by the very
  175. // nature of this error, developers will never be able to see the message
  176. // using the debugErrorMap (which is installed during auth initialization).
  177. return _a = {},
  178. _a["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  179. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  180. 'starting any other Firebase SDK.',
  181. _a;
  182. }
  183. /**
  184. * A verbose error map with detailed descriptions for most error codes.
  185. *
  186. * See discussion at {@link AuthErrorMap}
  187. *
  188. * @public
  189. */
  190. var debugErrorMap = _debugErrorMap;
  191. /**
  192. * A minimal error map with all verbose error messages stripped.
  193. *
  194. * See discussion at {@link AuthErrorMap}
  195. *
  196. * @public
  197. */
  198. var prodErrorMap = _prodErrorMap;
  199. var _DEFAULT_AUTH_ERROR_FACTORY = new util.ErrorFactory('auth', 'Firebase', _prodErrorMap());
  200. /**
  201. * A map of potential `Auth` error codes, for easier comparison with errors
  202. * thrown by the SDK.
  203. *
  204. * @remarks
  205. * Note that you can't tree-shake individual keys
  206. * in the map, so by using the map you might substantially increase your
  207. * bundle size.
  208. *
  209. * @public
  210. */
  211. var AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  212. ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
  213. ARGUMENT_ERROR: 'auth/argument-error',
  214. APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
  215. APP_NOT_INSTALLED: 'auth/app-not-installed',
  216. CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
  217. CODE_EXPIRED: 'auth/code-expired',
  218. CORDOVA_NOT_READY: 'auth/cordova-not-ready',
  219. CORS_UNSUPPORTED: 'auth/cors-unsupported',
  220. CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
  221. CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
  222. CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
  223. DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
  224. DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
  225. EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
  226. EMAIL_EXISTS: 'auth/email-already-in-use',
  227. EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
  228. EXPIRED_OOB_CODE: 'auth/expired-action-code',
  229. EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
  230. INTERNAL_ERROR: 'auth/internal-error',
  231. INVALID_API_KEY: 'auth/invalid-api-key',
  232. INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
  233. INVALID_APP_ID: 'auth/invalid-app-id',
  234. INVALID_AUTH: 'auth/invalid-user-token',
  235. INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
  236. INVALID_CERT_HASH: 'auth/invalid-cert-hash',
  237. INVALID_CODE: 'auth/invalid-verification-code',
  238. INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
  239. INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
  240. INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
  241. INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
  242. INVALID_EMAIL: 'auth/invalid-email',
  243. INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
  244. INVALID_IDP_RESPONSE: 'auth/invalid-credential',
  245. INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
  246. INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
  247. INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
  248. INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
  249. INVALID_OOB_CODE: 'auth/invalid-action-code',
  250. INVALID_ORIGIN: 'auth/unauthorized-domain',
  251. INVALID_PASSWORD: 'auth/wrong-password',
  252. INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
  253. INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
  254. INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
  255. INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
  256. INVALID_SENDER: 'auth/invalid-sender',
  257. INVALID_SESSION_INFO: 'auth/invalid-verification-id',
  258. INVALID_TENANT_ID: 'auth/invalid-tenant-id',
  259. MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
  260. MFA_REQUIRED: 'auth/multi-factor-auth-required',
  261. MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
  262. MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
  263. MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
  264. MISSING_CODE: 'auth/missing-verification-code',
  265. MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
  266. MISSING_IFRAME_START: 'auth/missing-iframe-start',
  267. MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
  268. MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
  269. MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
  270. MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
  271. MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
  272. MISSING_SESSION_INFO: 'auth/missing-verification-id',
  273. MODULE_DESTROYED: 'auth/app-deleted',
  274. NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
  275. NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
  276. NULL_USER: 'auth/null-user',
  277. NO_AUTH_EVENT: 'auth/no-auth-event',
  278. NO_SUCH_PROVIDER: 'auth/no-such-provider',
  279. OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
  280. OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
  281. POPUP_BLOCKED: 'auth/popup-blocked',
  282. POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
  283. PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
  284. QUOTA_EXCEEDED: 'auth/quota-exceeded',
  285. REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
  286. REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
  287. REJECTED_CREDENTIAL: 'auth/rejected-credential',
  288. SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
  289. SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
  290. TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
  291. TIMEOUT: 'auth/timeout',
  292. TOKEN_EXPIRED: 'auth/user-token-expired',
  293. TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
  294. UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
  295. UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
  296. UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
  297. UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
  298. UNVERIFIED_EMAIL: 'auth/unverified-email',
  299. USER_CANCELLED: 'auth/user-cancelled',
  300. USER_DELETED: 'auth/user-not-found',
  301. USER_DISABLED: 'auth/user-disabled',
  302. USER_MISMATCH: 'auth/user-mismatch',
  303. USER_SIGNED_OUT: 'auth/user-signed-out',
  304. WEAK_PASSWORD: 'auth/weak-password',
  305. WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
  306. ALREADY_INITIALIZED: 'auth/already-initialized'
  307. };
  308. /**
  309. * @license
  310. * Copyright 2020 Google LLC
  311. *
  312. * Licensed under the Apache License, Version 2.0 (the "License");
  313. * you may not use this file except in compliance with the License.
  314. * You may obtain a copy of the License at
  315. *
  316. * http://www.apache.org/licenses/LICENSE-2.0
  317. *
  318. * Unless required by applicable law or agreed to in writing, software
  319. * distributed under the License is distributed on an "AS IS" BASIS,
  320. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  321. * See the License for the specific language governing permissions and
  322. * limitations under the License.
  323. */
  324. var logClient = new logger.Logger('@firebase/auth');
  325. function _logError(msg) {
  326. var args = [];
  327. for (var _i = 1; _i < arguments.length; _i++) {
  328. args[_i - 1] = arguments[_i];
  329. }
  330. if (logClient.logLevel <= logger.LogLevel.ERROR) {
  331. logClient.error.apply(logClient, tslib.__spreadArray(["Auth (".concat(app.SDK_VERSION, "): ").concat(msg)], args, false));
  332. }
  333. }
  334. /**
  335. * @license
  336. * Copyright 2020 Google LLC
  337. *
  338. * Licensed under the Apache License, Version 2.0 (the "License");
  339. * you may not use this file except in compliance with the License.
  340. * You may obtain a copy of the License at
  341. *
  342. * http://www.apache.org/licenses/LICENSE-2.0
  343. *
  344. * Unless required by applicable law or agreed to in writing, software
  345. * distributed under the License is distributed on an "AS IS" BASIS,
  346. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  347. * See the License for the specific language governing permissions and
  348. * limitations under the License.
  349. */
  350. function _fail(authOrCode) {
  351. var rest = [];
  352. for (var _i = 1; _i < arguments.length; _i++) {
  353. rest[_i - 1] = arguments[_i];
  354. }
  355. throw createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest, false));
  356. }
  357. function _createError(authOrCode) {
  358. var rest = [];
  359. for (var _i = 1; _i < arguments.length; _i++) {
  360. rest[_i - 1] = arguments[_i];
  361. }
  362. return createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest, false));
  363. }
  364. function _errorWithCustomMessage(auth, code, message) {
  365. var _a;
  366. var errorMap = tslib.__assign(tslib.__assign({}, prodErrorMap()), (_a = {}, _a[code] = message, _a));
  367. var factory = new util.ErrorFactory('auth', 'Firebase', errorMap);
  368. return factory.create(code, {
  369. appName: auth.name
  370. });
  371. }
  372. function _assertInstanceOf(auth, object, instance) {
  373. var constructorInstance = instance;
  374. if (!(object instanceof constructorInstance)) {
  375. if (constructorInstance.name !== object.constructor.name) {
  376. _fail(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  377. }
  378. throw _errorWithCustomMessage(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, "Type of ".concat(object.constructor.name, " does not match expected instance.") +
  379. "Did you pass a reference from a different Auth SDK?");
  380. }
  381. }
  382. function createErrorInternal(authOrCode) {
  383. var _a;
  384. var rest = [];
  385. for (var _i = 1; _i < arguments.length; _i++) {
  386. rest[_i - 1] = arguments[_i];
  387. }
  388. if (typeof authOrCode !== 'string') {
  389. var code = rest[0];
  390. var fullParams = tslib.__spreadArray([], rest.slice(1), true);
  391. if (fullParams[0]) {
  392. fullParams[0].appName = authOrCode.name;
  393. }
  394. return (_a = authOrCode._errorFactory).create.apply(_a, tslib.__spreadArray([code], fullParams, false));
  395. }
  396. return _DEFAULT_AUTH_ERROR_FACTORY.create.apply(_DEFAULT_AUTH_ERROR_FACTORY, tslib.__spreadArray([authOrCode], rest, false));
  397. }
  398. function _assert(assertion, authOrCode) {
  399. var rest = [];
  400. for (var _i = 2; _i < arguments.length; _i++) {
  401. rest[_i - 2] = arguments[_i];
  402. }
  403. if (!assertion) {
  404. throw createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest, false));
  405. }
  406. }
  407. /**
  408. * Unconditionally fails, throwing an internal error with the given message.
  409. *
  410. * @param failure type of failure encountered
  411. * @throws Error
  412. */
  413. function debugFail(failure) {
  414. // Log the failure in addition to throw an exception, just in case the
  415. // exception is swallowed.
  416. var message = "INTERNAL ASSERTION FAILED: " + failure;
  417. _logError(message);
  418. // NOTE: We don't use FirebaseError here because these are internal failures
  419. // that cannot be handled by the user. (Also it would create a circular
  420. // dependency between the error and assert modules which doesn't work.)
  421. throw new Error(message);
  422. }
  423. /**
  424. * Fails if the given assertion condition is false, throwing an Error with the
  425. * given message if it did.
  426. *
  427. * @param assertion
  428. * @param message
  429. */
  430. function debugAssert(assertion, message) {
  431. if (!assertion) {
  432. debugFail(message);
  433. }
  434. }
  435. /**
  436. * @license
  437. * Copyright 2020 Google LLC
  438. *
  439. * Licensed under the Apache License, Version 2.0 (the "License");
  440. * you may not use this file except in compliance with the License.
  441. * You may obtain a copy of the License at
  442. *
  443. * http://www.apache.org/licenses/LICENSE-2.0
  444. *
  445. * Unless required by applicable law or agreed to in writing, software
  446. * distributed under the License is distributed on an "AS IS" BASIS,
  447. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  448. * See the License for the specific language governing permissions and
  449. * limitations under the License.
  450. */
  451. var instanceCache = new Map();
  452. function _getInstance(cls) {
  453. debugAssert(cls instanceof Function, 'Expected a class definition');
  454. var instance = instanceCache.get(cls);
  455. if (instance) {
  456. debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
  457. return instance;
  458. }
  459. instance = new cls();
  460. instanceCache.set(cls, instance);
  461. return instance;
  462. }
  463. /**
  464. * @license
  465. * Copyright 2020 Google LLC
  466. *
  467. * Licensed under the Apache License, Version 2.0 (the "License");
  468. * you may not use this file except in compliance with the License.
  469. * You may obtain a copy of the License at
  470. *
  471. * http://www.apache.org/licenses/LICENSE-2.0
  472. *
  473. * Unless required by applicable law or agreed to in writing, software
  474. * distributed under the License is distributed on an "AS IS" BASIS,
  475. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  476. * See the License for the specific language governing permissions and
  477. * limitations under the License.
  478. */
  479. /**
  480. * Initializes an {@link Auth} instance with fine-grained control over
  481. * {@link Dependencies}.
  482. *
  483. * @remarks
  484. *
  485. * This function allows more control over the {@link Auth} instance than
  486. * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
  487. * the {@link Dependencies}. In general, `getAuth` is the easiest way to
  488. * initialize Auth and works for most use cases. Use `initializeAuth` if you
  489. * need control over which persistence layer is used, or to minimize bundle
  490. * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
  491. *
  492. * For example, if your app only uses anonymous accounts and you only want
  493. * accounts saved for the current session, initialize `Auth` with:
  494. *
  495. * ```js
  496. * const auth = initializeAuth(app, {
  497. * persistence: browserSessionPersistence,
  498. * popupRedirectResolver: undefined,
  499. * });
  500. * ```
  501. *
  502. * @public
  503. */
  504. function initializeAuth(app$1, deps) {
  505. var provider = app._getProvider(app$1, 'auth');
  506. if (provider.isInitialized()) {
  507. var auth_1 = provider.getImmediate();
  508. var initialOptions = provider.getOptions();
  509. if (util.deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
  510. return auth_1;
  511. }
  512. else {
  513. _fail(auth_1, "already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */);
  514. }
  515. }
  516. var auth = provider.initialize({ options: deps });
  517. return auth;
  518. }
  519. function _initializeAuthInstance(auth, deps) {
  520. var persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  521. var hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  522. if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
  523. auth._updateErrorMap(deps.errorMap);
  524. }
  525. // This promise is intended to float; auth initialization happens in the
  526. // background, meanwhile the auth object may be used by the app.
  527. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  528. auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
  529. }
  530. /**
  531. * @license
  532. * Copyright 2020 Google LLC
  533. *
  534. * Licensed under the Apache License, Version 2.0 (the "License");
  535. * you may not use this file except in compliance with the License.
  536. * You may obtain a copy of the License at
  537. *
  538. * http://www.apache.org/licenses/LICENSE-2.0
  539. *
  540. * Unless required by applicable law or agreed to in writing, software
  541. * distributed under the License is distributed on an "AS IS" BASIS,
  542. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  543. * See the License for the specific language governing permissions and
  544. * limitations under the License.
  545. */
  546. function _getCurrentUrl() {
  547. var _a;
  548. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
  549. }
  550. function _isHttpOrHttps() {
  551. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  552. }
  553. function _getCurrentScheme() {
  554. var _a;
  555. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
  556. }
  557. /**
  558. * @license
  559. * Copyright 2020 Google LLC
  560. *
  561. * Licensed under the Apache License, Version 2.0 (the "License");
  562. * you may not use this file except in compliance with the License.
  563. * You may obtain a copy of the License at
  564. *
  565. * http://www.apache.org/licenses/LICENSE-2.0
  566. *
  567. * Unless required by applicable law or agreed to in writing, software
  568. * distributed under the License is distributed on an "AS IS" BASIS,
  569. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  570. * See the License for the specific language governing permissions and
  571. * limitations under the License.
  572. */
  573. /**
  574. * Determine whether the browser is working online
  575. */
  576. function _isOnline() {
  577. if (typeof navigator !== 'undefined' &&
  578. navigator &&
  579. 'onLine' in navigator &&
  580. typeof navigator.onLine === 'boolean' &&
  581. // Apply only for traditional web apps and Chrome extensions.
  582. // This is especially true for Cordova apps which have unreliable
  583. // navigator.onLine behavior unless cordova-plugin-network-information is
  584. // installed which overwrites the native navigator.onLine value and
  585. // defines navigator.connection.
  586. (_isHttpOrHttps() || util.isBrowserExtension() || 'connection' in navigator)) {
  587. return navigator.onLine;
  588. }
  589. // If we can't determine the state, assume it is online.
  590. return true;
  591. }
  592. function _getUserLanguage() {
  593. if (typeof navigator === 'undefined') {
  594. return null;
  595. }
  596. var navigatorLanguage = navigator;
  597. return (
  598. // Most reliable, but only supported in Chrome/Firefox.
  599. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  600. // Supported in most browsers, but returns the language of the browser
  601. // UI, not the language set in browser settings.
  602. navigatorLanguage.language ||
  603. // Couldn't determine language.
  604. null);
  605. }
  606. /**
  607. * @license
  608. * Copyright 2020 Google LLC
  609. *
  610. * Licensed under the Apache License, Version 2.0 (the "License");
  611. * you may not use this file except in compliance with the License.
  612. * You may obtain a copy of the License at
  613. *
  614. * http://www.apache.org/licenses/LICENSE-2.0
  615. *
  616. * Unless required by applicable law or agreed to in writing, software
  617. * distributed under the License is distributed on an "AS IS" BASIS,
  618. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  619. * See the License for the specific language governing permissions and
  620. * limitations under the License.
  621. */
  622. /**
  623. * A structure to help pick between a range of long and short delay durations
  624. * depending on the current environment. In general, the long delay is used for
  625. * mobile environments whereas short delays are used for desktop environments.
  626. */
  627. var Delay = /** @class */ (function () {
  628. function Delay(shortDelay, longDelay) {
  629. this.shortDelay = shortDelay;
  630. this.longDelay = longDelay;
  631. // Internal error when improperly initialized.
  632. debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
  633. this.isMobile = util.isMobileCordova() || util.isReactNative();
  634. }
  635. Delay.prototype.get = function () {
  636. if (!_isOnline()) {
  637. // Pick the shorter timeout.
  638. return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);
  639. }
  640. // If running in a mobile environment, return the long delay, otherwise
  641. // return the short delay.
  642. // This could be improved in the future to dynamically change based on other
  643. // variables instead of just reading the current environment.
  644. return this.isMobile ? this.longDelay : this.shortDelay;
  645. };
  646. return Delay;
  647. }());
  648. /**
  649. * @license
  650. * Copyright 2020 Google LLC
  651. *
  652. * Licensed under the Apache License, Version 2.0 (the "License");
  653. * you may not use this file except in compliance with the License.
  654. * You may obtain a copy of the License at
  655. *
  656. * http://www.apache.org/licenses/LICENSE-2.0
  657. *
  658. * Unless required by applicable law or agreed to in writing, software
  659. * distributed under the License is distributed on an "AS IS" BASIS,
  660. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  661. * See the License for the specific language governing permissions and
  662. * limitations under the License.
  663. */
  664. function _emulatorUrl(config, path) {
  665. debugAssert(config.emulator, 'Emulator should always be set here');
  666. var url = config.emulator.url;
  667. if (!path) {
  668. return url;
  669. }
  670. return "".concat(url).concat(path.startsWith('/') ? path.slice(1) : path);
  671. }
  672. /**
  673. * @license
  674. * Copyright 2020 Google LLC
  675. *
  676. * Licensed under the Apache License, Version 2.0 (the "License");
  677. * you may not use this file except in compliance with the License.
  678. * You may obtain a copy of the License at
  679. *
  680. * http://www.apache.org/licenses/LICENSE-2.0
  681. *
  682. * Unless required by applicable law or agreed to in writing, software
  683. * distributed under the License is distributed on an "AS IS" BASIS,
  684. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  685. * See the License for the specific language governing permissions and
  686. * limitations under the License.
  687. */
  688. var FetchProvider = /** @class */ (function () {
  689. function FetchProvider() {
  690. }
  691. FetchProvider.initialize = function (fetchImpl, headersImpl, responseImpl) {
  692. this.fetchImpl = fetchImpl;
  693. if (headersImpl) {
  694. this.headersImpl = headersImpl;
  695. }
  696. if (responseImpl) {
  697. this.responseImpl = responseImpl;
  698. }
  699. };
  700. FetchProvider.fetch = function () {
  701. if (this.fetchImpl) {
  702. return this.fetchImpl;
  703. }
  704. if (typeof self !== 'undefined' && 'fetch' in self) {
  705. return self.fetch;
  706. }
  707. debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  708. };
  709. FetchProvider.headers = function () {
  710. if (this.headersImpl) {
  711. return this.headersImpl;
  712. }
  713. if (typeof self !== 'undefined' && 'Headers' in self) {
  714. return self.Headers;
  715. }
  716. debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  717. };
  718. FetchProvider.response = function () {
  719. if (this.responseImpl) {
  720. return this.responseImpl;
  721. }
  722. if (typeof self !== 'undefined' && 'Response' in self) {
  723. return self.Response;
  724. }
  725. debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  726. };
  727. return FetchProvider;
  728. }());
  729. /**
  730. * @license
  731. * Copyright 2020 Google LLC
  732. *
  733. * Licensed under the Apache License, Version 2.0 (the "License");
  734. * you may not use this file except in compliance with the License.
  735. * You may obtain a copy of the License at
  736. *
  737. * http://www.apache.org/licenses/LICENSE-2.0
  738. *
  739. * Unless required by applicable law or agreed to in writing, software
  740. * distributed under the License is distributed on an "AS IS" BASIS,
  741. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  742. * See the License for the specific language governing permissions and
  743. * limitations under the License.
  744. */
  745. var _a$1;
  746. /**
  747. * Map from errors returned by the server to errors to developer visible errors
  748. */
  749. var SERVER_ERROR_MAP = (_a$1 = {},
  750. // Custom token errors.
  751. _a$1["CREDENTIAL_MISMATCH" /* ServerError.CREDENTIAL_MISMATCH */] = "custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */,
  752. // This can only happen if the SDK sends a bad request.
  753. _a$1["MISSING_CUSTOM_TOKEN" /* ServerError.MISSING_CUSTOM_TOKEN */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  754. // Create Auth URI errors.
  755. _a$1["INVALID_IDENTIFIER" /* ServerError.INVALID_IDENTIFIER */] = "invalid-email" /* AuthErrorCode.INVALID_EMAIL */,
  756. // This can only happen if the SDK sends a bad request.
  757. _a$1["MISSING_CONTINUE_URI" /* ServerError.MISSING_CONTINUE_URI */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  758. // Sign in with email and password errors (some apply to sign up too).
  759. _a$1["INVALID_PASSWORD" /* ServerError.INVALID_PASSWORD */] = "wrong-password" /* AuthErrorCode.INVALID_PASSWORD */,
  760. // This can only happen if the SDK sends a bad request.
  761. _a$1["MISSING_PASSWORD" /* ServerError.MISSING_PASSWORD */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  762. // Sign up with email and password errors.
  763. _a$1["EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */] = "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */,
  764. _a$1["PASSWORD_LOGIN_DISABLED" /* ServerError.PASSWORD_LOGIN_DISABLED */] = "operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,
  765. // Verify assertion for sign in with credential errors:
  766. _a$1["INVALID_IDP_RESPONSE" /* ServerError.INVALID_IDP_RESPONSE */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  767. _a$1["INVALID_PENDING_TOKEN" /* ServerError.INVALID_PENDING_TOKEN */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  768. _a$1["FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */] = "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,
  769. // This can only happen if the SDK sends a bad request.
  770. _a$1["MISSING_REQ_TYPE" /* ServerError.MISSING_REQ_TYPE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  771. // Send Password reset email errors:
  772. _a$1["EMAIL_NOT_FOUND" /* ServerError.EMAIL_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  773. _a$1["RESET_PASSWORD_EXCEED_LIMIT" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  774. _a$1["EXPIRED_OOB_CODE" /* ServerError.EXPIRED_OOB_CODE */] = "expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */,
  775. _a$1["INVALID_OOB_CODE" /* ServerError.INVALID_OOB_CODE */] = "invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */,
  776. // This can only happen if the SDK sends a bad request.
  777. _a$1["MISSING_OOB_CODE" /* ServerError.MISSING_OOB_CODE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  778. // Operations that require ID token in request:
  779. _a$1["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = "requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
  780. _a$1["INVALID_ID_TOKEN" /* ServerError.INVALID_ID_TOKEN */] = "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */,
  781. _a$1["TOKEN_EXPIRED" /* ServerError.TOKEN_EXPIRED */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  782. _a$1["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  783. // Other errors.
  784. _a$1["TOO_MANY_ATTEMPTS_TRY_LATER" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  785. // Phone Auth related errors.
  786. _a$1["INVALID_CODE" /* ServerError.INVALID_CODE */] = "invalid-verification-code" /* AuthErrorCode.INVALID_CODE */,
  787. _a$1["INVALID_SESSION_INFO" /* ServerError.INVALID_SESSION_INFO */] = "invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */,
  788. _a$1["INVALID_TEMPORARY_PROOF" /* ServerError.INVALID_TEMPORARY_PROOF */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  789. _a$1["MISSING_SESSION_INFO" /* ServerError.MISSING_SESSION_INFO */] = "missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */,
  790. _a$1["SESSION_EXPIRED" /* ServerError.SESSION_EXPIRED */] = "code-expired" /* AuthErrorCode.CODE_EXPIRED */,
  791. // Other action code errors when additional settings passed.
  792. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  793. // This is OK as this error will be caught by client side validation.
  794. _a$1["MISSING_ANDROID_PACKAGE_NAME" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */] = "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,
  795. _a$1["UNAUTHORIZED_DOMAIN" /* ServerError.UNAUTHORIZED_DOMAIN */] = "unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,
  796. // getProjectConfig errors when clientId is passed.
  797. _a$1["INVALID_OAUTH_CLIENT_ID" /* ServerError.INVALID_OAUTH_CLIENT_ID */] = "invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,
  798. // User actions (sign-up or deletion) disabled errors.
  799. _a$1["ADMIN_ONLY_OPERATION" /* ServerError.ADMIN_ONLY_OPERATION */] = "admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,
  800. // Multi factor related errors.
  801. _a$1["INVALID_MFA_PENDING_CREDENTIAL" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */] = "invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */,
  802. _a$1["MFA_ENROLLMENT_NOT_FOUND" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */] = "multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,
  803. _a$1["MISSING_MFA_ENROLLMENT_ID" /* ServerError.MISSING_MFA_ENROLLMENT_ID */] = "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */,
  804. _a$1["MISSING_MFA_PENDING_CREDENTIAL" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */] = "missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */,
  805. _a$1["SECOND_FACTOR_EXISTS" /* ServerError.SECOND_FACTOR_EXISTS */] = "second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,
  806. _a$1["SECOND_FACTOR_LIMIT_EXCEEDED" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */] = "maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,
  807. // Blocking functions related errors.
  808. _a$1["BLOCKING_FUNCTION_ERROR_RESPONSE" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  809. _a$1);
  810. /**
  811. * @license
  812. * Copyright 2020 Google LLC
  813. *
  814. * Licensed under the Apache License, Version 2.0 (the "License");
  815. * you may not use this file except in compliance with the License.
  816. * You may obtain a copy of the License at
  817. *
  818. * http://www.apache.org/licenses/LICENSE-2.0
  819. *
  820. * Unless required by applicable law or agreed to in writing, software
  821. * distributed under the License is distributed on an "AS IS" BASIS,
  822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  823. * See the License for the specific language governing permissions and
  824. * limitations under the License.
  825. */
  826. var DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
  827. function _addTidIfNecessary(auth, request) {
  828. if (auth.tenantId && !request.tenantId) {
  829. return tslib.__assign(tslib.__assign({}, request), { tenantId: auth.tenantId });
  830. }
  831. return request;
  832. }
  833. function _performApiRequest(auth, method, path, request, customErrorMap) {
  834. if (customErrorMap === void 0) { customErrorMap = {}; }
  835. return tslib.__awaiter(this, void 0, void 0, function () {
  836. var _this = this;
  837. return tslib.__generator(this, function (_a) {
  838. return [2 /*return*/, _performFetchWithErrorHandling(auth, customErrorMap, function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  839. var body, params, query, headers;
  840. return tslib.__generator(this, function (_a) {
  841. switch (_a.label) {
  842. case 0:
  843. body = {};
  844. params = {};
  845. if (request) {
  846. if (method === "GET" /* HttpMethod.GET */) {
  847. params = request;
  848. }
  849. else {
  850. body = {
  851. body: JSON.stringify(request)
  852. };
  853. }
  854. }
  855. query = util.querystring(tslib.__assign({ key: auth.config.apiKey }, params)).slice(1);
  856. return [4 /*yield*/, auth._getAdditionalHeaders()];
  857. case 1:
  858. headers = _a.sent();
  859. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/json';
  860. if (auth.languageCode) {
  861. headers["X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;
  862. }
  863. return [2 /*return*/, FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), tslib.__assign({ method: method, headers: headers, referrerPolicy: 'no-referrer' }, body))];
  864. }
  865. });
  866. }); })];
  867. });
  868. });
  869. }
  870. function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  871. return tslib.__awaiter(this, void 0, void 0, function () {
  872. var errorMap, networkTimeout, response, json, errorMessage, _a, serverErrorCode, serverErrorMessage, authError, e_1;
  873. return tslib.__generator(this, function (_b) {
  874. switch (_b.label) {
  875. case 0:
  876. auth._canInitEmulator = false;
  877. errorMap = tslib.__assign(tslib.__assign({}, SERVER_ERROR_MAP), customErrorMap);
  878. _b.label = 1;
  879. case 1:
  880. _b.trys.push([1, 4, , 5]);
  881. networkTimeout = new NetworkTimeout(auth);
  882. return [4 /*yield*/, Promise.race([
  883. fetchFn(),
  884. networkTimeout.promise
  885. ])];
  886. case 2:
  887. response = _b.sent();
  888. // If we've reached this point, the fetch succeeded and the networkTimeout
  889. // didn't throw; clear the network timeout delay so that Node won't hang
  890. networkTimeout.clearNetworkTimeout();
  891. return [4 /*yield*/, response.json()];
  892. case 3:
  893. json = _b.sent();
  894. if ('needConfirmation' in json) {
  895. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, json);
  896. }
  897. if (response.ok && !('errorMessage' in json)) {
  898. return [2 /*return*/, json];
  899. }
  900. else {
  901. errorMessage = response.ok ? json.errorMessage : json.error.message;
  902. _a = errorMessage.split(' : '), serverErrorCode = _a[0], serverErrorMessage = _a[1];
  903. if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {
  904. throw _makeTaggedError(auth, "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);
  905. }
  906. else if (serverErrorCode === "EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */) {
  907. throw _makeTaggedError(auth, "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */, json);
  908. }
  909. else if (serverErrorCode === "USER_DISABLED" /* ServerError.USER_DISABLED */) {
  910. throw _makeTaggedError(auth, "user-disabled" /* AuthErrorCode.USER_DISABLED */, json);
  911. }
  912. authError = errorMap[serverErrorCode] ||
  913. serverErrorCode
  914. .toLowerCase()
  915. .replace(/[_\s]+/g, '-');
  916. if (serverErrorMessage) {
  917. throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
  918. }
  919. else {
  920. _fail(auth, authError);
  921. }
  922. }
  923. return [3 /*break*/, 5];
  924. case 4:
  925. e_1 = _b.sent();
  926. if (e_1 instanceof util.FirebaseError) {
  927. throw e_1;
  928. }
  929. _fail(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  930. return [3 /*break*/, 5];
  931. case 5: return [2 /*return*/];
  932. }
  933. });
  934. });
  935. }
  936. function _performSignInRequest(auth, method, path, request, customErrorMap) {
  937. if (customErrorMap === void 0) { customErrorMap = {}; }
  938. return tslib.__awaiter(this, void 0, void 0, function () {
  939. var serverResponse;
  940. return tslib.__generator(this, function (_a) {
  941. switch (_a.label) {
  942. case 0: return [4 /*yield*/, _performApiRequest(auth, method, path, request, customErrorMap)];
  943. case 1:
  944. serverResponse = (_a.sent());
  945. if ('mfaPendingCredential' in serverResponse) {
  946. _fail(auth, "multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */, {
  947. _serverResponse: serverResponse
  948. });
  949. }
  950. return [2 /*return*/, serverResponse];
  951. }
  952. });
  953. });
  954. }
  955. function _getFinalTarget(auth, host, path, query) {
  956. var base = "".concat(host).concat(path, "?").concat(query);
  957. if (!auth.config.emulator) {
  958. return "".concat(auth.config.apiScheme, "://").concat(base);
  959. }
  960. return _emulatorUrl(auth.config, base);
  961. }
  962. var NetworkTimeout = /** @class */ (function () {
  963. function NetworkTimeout(auth) {
  964. var _this = this;
  965. this.auth = auth;
  966. // Node timers and browser timers are fundamentally incompatible, but we
  967. // don't care about the value here
  968. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  969. this.timer = null;
  970. this.promise = new Promise(function (_, reject) {
  971. _this.timer = setTimeout(function () {
  972. return reject(_createError(_this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  973. }, DEFAULT_API_TIMEOUT_MS.get());
  974. });
  975. }
  976. NetworkTimeout.prototype.clearNetworkTimeout = function () {
  977. clearTimeout(this.timer);
  978. };
  979. return NetworkTimeout;
  980. }());
  981. function _makeTaggedError(auth, code, response) {
  982. var errorParams = {
  983. appName: auth.name
  984. };
  985. if (response.email) {
  986. errorParams.email = response.email;
  987. }
  988. if (response.phoneNumber) {
  989. errorParams.phoneNumber = response.phoneNumber;
  990. }
  991. var error = _createError(auth, code, errorParams);
  992. // We know customData is defined on error because errorParams is defined
  993. error.customData._tokenResponse = response;
  994. return error;
  995. }
  996. /**
  997. * @license
  998. * Copyright 2020 Google LLC
  999. *
  1000. * Licensed under the Apache License, Version 2.0 (the "License");
  1001. * you may not use this file except in compliance with the License.
  1002. * You may obtain a copy of the License at
  1003. *
  1004. * http://www.apache.org/licenses/LICENSE-2.0
  1005. *
  1006. * Unless required by applicable law or agreed to in writing, software
  1007. * distributed under the License is distributed on an "AS IS" BASIS,
  1008. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1009. * See the License for the specific language governing permissions and
  1010. * limitations under the License.
  1011. */
  1012. function deleteAccount(auth, request) {
  1013. return tslib.__awaiter(this, void 0, void 0, function () {
  1014. return tslib.__generator(this, function (_a) {
  1015. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:delete" /* Endpoint.DELETE_ACCOUNT */, request)];
  1016. });
  1017. });
  1018. }
  1019. function deleteLinkedAccounts(auth, request) {
  1020. return tslib.__awaiter(this, void 0, void 0, function () {
  1021. return tslib.__generator(this, function (_a) {
  1022. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  1023. });
  1024. });
  1025. }
  1026. function getAccountInfo(auth, request) {
  1027. return tslib.__awaiter(this, void 0, void 0, function () {
  1028. return tslib.__generator(this, function (_a) {
  1029. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:lookup" /* Endpoint.GET_ACCOUNT_INFO */, request)];
  1030. });
  1031. });
  1032. }
  1033. /**
  1034. * @license
  1035. * Copyright 2020 Google LLC
  1036. *
  1037. * Licensed under the Apache License, Version 2.0 (the "License");
  1038. * you may not use this file except in compliance with the License.
  1039. * You may obtain a copy of the License at
  1040. *
  1041. * http://www.apache.org/licenses/LICENSE-2.0
  1042. *
  1043. * Unless required by applicable law or agreed to in writing, software
  1044. * distributed under the License is distributed on an "AS IS" BASIS,
  1045. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1046. * See the License for the specific language governing permissions and
  1047. * limitations under the License.
  1048. */
  1049. function utcTimestampToDateString(utcTimestamp) {
  1050. if (!utcTimestamp) {
  1051. return undefined;
  1052. }
  1053. try {
  1054. // Convert to date object.
  1055. var date = new Date(Number(utcTimestamp));
  1056. // Test date is valid.
  1057. if (!isNaN(date.getTime())) {
  1058. // Convert to UTC date string.
  1059. return date.toUTCString();
  1060. }
  1061. }
  1062. catch (e) {
  1063. // Do nothing. undefined will be returned.
  1064. }
  1065. return undefined;
  1066. }
  1067. /**
  1068. * @license
  1069. * Copyright 2020 Google LLC
  1070. *
  1071. * Licensed under the Apache License, Version 2.0 (the "License");
  1072. * you may not use this file except in compliance with the License.
  1073. * You may obtain a copy of the License at
  1074. *
  1075. * http://www.apache.org/licenses/LICENSE-2.0
  1076. *
  1077. * Unless required by applicable law or agreed to in writing, software
  1078. * distributed under the License is distributed on an "AS IS" BASIS,
  1079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1080. * See the License for the specific language governing permissions and
  1081. * limitations under the License.
  1082. */
  1083. /**
  1084. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
  1085. *
  1086. * @remarks
  1087. * Returns the current token if it has not expired or if it will not expire in the next five
  1088. * minutes. Otherwise, this will refresh the token and return a new one.
  1089. *
  1090. * @param user - The user.
  1091. * @param forceRefresh - Force refresh regardless of token expiration.
  1092. *
  1093. * @public
  1094. */
  1095. function getIdToken(user, forceRefresh) {
  1096. if (forceRefresh === void 0) { forceRefresh = false; }
  1097. return util.getModularInstance(user).getIdToken(forceRefresh);
  1098. }
  1099. /**
  1100. * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.
  1101. *
  1102. * @remarks
  1103. * Returns the current token if it has not expired or if it will not expire in the next five
  1104. * minutes. Otherwise, this will refresh the token and return a new one.
  1105. *
  1106. * @param user - The user.
  1107. * @param forceRefresh - Force refresh regardless of token expiration.
  1108. *
  1109. * @public
  1110. */
  1111. function getIdTokenResult(user, forceRefresh) {
  1112. if (forceRefresh === void 0) { forceRefresh = false; }
  1113. return tslib.__awaiter(this, void 0, void 0, function () {
  1114. var userInternal, token, claims, firebase, signInProvider;
  1115. return tslib.__generator(this, function (_a) {
  1116. switch (_a.label) {
  1117. case 0:
  1118. userInternal = util.getModularInstance(user);
  1119. return [4 /*yield*/, userInternal.getIdToken(forceRefresh)];
  1120. case 1:
  1121. token = _a.sent();
  1122. claims = _parseToken(token);
  1123. _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1124. firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
  1125. signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
  1126. return [2 /*return*/, {
  1127. claims: claims,
  1128. token: token,
  1129. authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
  1130. issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
  1131. expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
  1132. signInProvider: signInProvider || null,
  1133. signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
  1134. }];
  1135. }
  1136. });
  1137. });
  1138. }
  1139. function secondsStringToMilliseconds(seconds) {
  1140. return Number(seconds) * 1000;
  1141. }
  1142. function _parseToken(token) {
  1143. var _a = token.split('.'), algorithm = _a[0], payload = _a[1], signature = _a[2];
  1144. if (algorithm === undefined ||
  1145. payload === undefined ||
  1146. signature === undefined) {
  1147. _logError('JWT malformed, contained fewer than 3 sections');
  1148. return null;
  1149. }
  1150. try {
  1151. var decoded = util.base64Decode(payload);
  1152. if (!decoded) {
  1153. _logError('Failed to decode base64 JWT payload');
  1154. return null;
  1155. }
  1156. return JSON.parse(decoded);
  1157. }
  1158. catch (e) {
  1159. _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());
  1160. return null;
  1161. }
  1162. }
  1163. /**
  1164. * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
  1165. */
  1166. function _tokenExpiresIn(token) {
  1167. var parsedToken = _parseToken(token);
  1168. _assert(parsedToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1169. _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1170. _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1171. return Number(parsedToken.exp) - Number(parsedToken.iat);
  1172. }
  1173. /**
  1174. * @license
  1175. * Copyright 2020 Google LLC
  1176. *
  1177. * Licensed under the Apache License, Version 2.0 (the "License");
  1178. * you may not use this file except in compliance with the License.
  1179. * You may obtain a copy of the License at
  1180. *
  1181. * http://www.apache.org/licenses/LICENSE-2.0
  1182. *
  1183. * Unless required by applicable law or agreed to in writing, software
  1184. * distributed under the License is distributed on an "AS IS" BASIS,
  1185. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1186. * See the License for the specific language governing permissions and
  1187. * limitations under the License.
  1188. */
  1189. function _logoutIfInvalidated(user, promise, bypassAuthState) {
  1190. if (bypassAuthState === void 0) { bypassAuthState = false; }
  1191. return tslib.__awaiter(this, void 0, void 0, function () {
  1192. var e_1;
  1193. return tslib.__generator(this, function (_a) {
  1194. switch (_a.label) {
  1195. case 0:
  1196. if (bypassAuthState) {
  1197. return [2 /*return*/, promise];
  1198. }
  1199. _a.label = 1;
  1200. case 1:
  1201. _a.trys.push([1, 3, , 6]);
  1202. return [4 /*yield*/, promise];
  1203. case 2: return [2 /*return*/, _a.sent()];
  1204. case 3:
  1205. e_1 = _a.sent();
  1206. if (!(e_1 instanceof util.FirebaseError && isUserInvalidated(e_1))) return [3 /*break*/, 5];
  1207. if (!(user.auth.currentUser === user)) return [3 /*break*/, 5];
  1208. return [4 /*yield*/, user.auth.signOut()];
  1209. case 4:
  1210. _a.sent();
  1211. _a.label = 5;
  1212. case 5: throw e_1;
  1213. case 6: return [2 /*return*/];
  1214. }
  1215. });
  1216. });
  1217. }
  1218. function isUserInvalidated(_a) {
  1219. var code = _a.code;
  1220. return (code === "auth/".concat("user-disabled" /* AuthErrorCode.USER_DISABLED */) ||
  1221. code === "auth/".concat("user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */));
  1222. }
  1223. /**
  1224. * @license
  1225. * Copyright 2020 Google LLC
  1226. *
  1227. * Licensed under the Apache License, Version 2.0 (the "License");
  1228. * you may not use this file except in compliance with the License.
  1229. * You may obtain a copy of the License at
  1230. *
  1231. * http://www.apache.org/licenses/LICENSE-2.0
  1232. *
  1233. * Unless required by applicable law or agreed to in writing, software
  1234. * distributed under the License is distributed on an "AS IS" BASIS,
  1235. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1236. * See the License for the specific language governing permissions and
  1237. * limitations under the License.
  1238. */
  1239. var ProactiveRefresh = /** @class */ (function () {
  1240. function ProactiveRefresh(user) {
  1241. this.user = user;
  1242. this.isRunning = false;
  1243. // Node timers and browser timers return fundamentally different types.
  1244. // We don't actually care what the value is but TS won't accept unknown and
  1245. // we can't cast properly in both environments.
  1246. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1247. this.timerId = null;
  1248. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1249. }
  1250. ProactiveRefresh.prototype._start = function () {
  1251. if (this.isRunning) {
  1252. return;
  1253. }
  1254. this.isRunning = true;
  1255. this.schedule();
  1256. };
  1257. ProactiveRefresh.prototype._stop = function () {
  1258. if (!this.isRunning) {
  1259. return;
  1260. }
  1261. this.isRunning = false;
  1262. if (this.timerId !== null) {
  1263. clearTimeout(this.timerId);
  1264. }
  1265. };
  1266. ProactiveRefresh.prototype.getInterval = function (wasError) {
  1267. var _a;
  1268. if (wasError) {
  1269. var interval = this.errorBackoff;
  1270. this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);
  1271. return interval;
  1272. }
  1273. else {
  1274. // Reset the error backoff
  1275. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1276. var expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
  1277. var interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;
  1278. return Math.max(0, interval);
  1279. }
  1280. };
  1281. ProactiveRefresh.prototype.schedule = function (wasError) {
  1282. var _this = this;
  1283. if (wasError === void 0) { wasError = false; }
  1284. if (!this.isRunning) {
  1285. // Just in case...
  1286. return;
  1287. }
  1288. var interval = this.getInterval(wasError);
  1289. this.timerId = setTimeout(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  1290. return tslib.__generator(this, function (_a) {
  1291. switch (_a.label) {
  1292. case 0: return [4 /*yield*/, this.iteration()];
  1293. case 1:
  1294. _a.sent();
  1295. return [2 /*return*/];
  1296. }
  1297. });
  1298. }); }, interval);
  1299. };
  1300. ProactiveRefresh.prototype.iteration = function () {
  1301. return tslib.__awaiter(this, void 0, void 0, function () {
  1302. var e_1;
  1303. return tslib.__generator(this, function (_a) {
  1304. switch (_a.label) {
  1305. case 0:
  1306. _a.trys.push([0, 2, , 3]);
  1307. return [4 /*yield*/, this.user.getIdToken(true)];
  1308. case 1:
  1309. _a.sent();
  1310. return [3 /*break*/, 3];
  1311. case 2:
  1312. e_1 = _a.sent();
  1313. // Only retry on network errors
  1314. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) ===
  1315. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  1316. this.schedule(/* wasError */ true);
  1317. }
  1318. return [2 /*return*/];
  1319. case 3:
  1320. this.schedule();
  1321. return [2 /*return*/];
  1322. }
  1323. });
  1324. });
  1325. };
  1326. return ProactiveRefresh;
  1327. }());
  1328. /**
  1329. * @license
  1330. * Copyright 2020 Google LLC
  1331. *
  1332. * Licensed under the Apache License, Version 2.0 (the "License");
  1333. * you may not use this file except in compliance with the License.
  1334. * You may obtain a copy of the License at
  1335. *
  1336. * http://www.apache.org/licenses/LICENSE-2.0
  1337. *
  1338. * Unless required by applicable law or agreed to in writing, software
  1339. * distributed under the License is distributed on an "AS IS" BASIS,
  1340. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1341. * See the License for the specific language governing permissions and
  1342. * limitations under the License.
  1343. */
  1344. var UserMetadata = /** @class */ (function () {
  1345. function UserMetadata(createdAt, lastLoginAt) {
  1346. this.createdAt = createdAt;
  1347. this.lastLoginAt = lastLoginAt;
  1348. this._initializeTime();
  1349. }
  1350. UserMetadata.prototype._initializeTime = function () {
  1351. this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
  1352. this.creationTime = utcTimestampToDateString(this.createdAt);
  1353. };
  1354. UserMetadata.prototype._copy = function (metadata) {
  1355. this.createdAt = metadata.createdAt;
  1356. this.lastLoginAt = metadata.lastLoginAt;
  1357. this._initializeTime();
  1358. };
  1359. UserMetadata.prototype.toJSON = function () {
  1360. return {
  1361. createdAt: this.createdAt,
  1362. lastLoginAt: this.lastLoginAt
  1363. };
  1364. };
  1365. return UserMetadata;
  1366. }());
  1367. /**
  1368. * @license
  1369. * Copyright 2019 Google LLC
  1370. *
  1371. * Licensed under the Apache License, Version 2.0 (the "License");
  1372. * you may not use this file except in compliance with the License.
  1373. * You may obtain a copy of the License at
  1374. *
  1375. * http://www.apache.org/licenses/LICENSE-2.0
  1376. *
  1377. * Unless required by applicable law or agreed to in writing, software
  1378. * distributed under the License is distributed on an "AS IS" BASIS,
  1379. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1380. * See the License for the specific language governing permissions and
  1381. * limitations under the License.
  1382. */
  1383. function _reloadWithoutSaving(user) {
  1384. var _a;
  1385. return tslib.__awaiter(this, void 0, void 0, function () {
  1386. var auth, idToken, response, coreAccount, newProviderData, providerData, oldIsAnonymous, newIsAnonymous, isAnonymous, updates;
  1387. return tslib.__generator(this, function (_b) {
  1388. switch (_b.label) {
  1389. case 0:
  1390. auth = user.auth;
  1391. return [4 /*yield*/, user.getIdToken()];
  1392. case 1:
  1393. idToken = _b.sent();
  1394. return [4 /*yield*/, _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: idToken }))];
  1395. case 2:
  1396. response = _b.sent();
  1397. _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1398. coreAccount = response.users[0];
  1399. user._notifyReloadListener(coreAccount);
  1400. newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
  1401. ? extractProviderData(coreAccount.providerUserInfo)
  1402. : [];
  1403. providerData = mergeProviderData(user.providerData, newProviderData);
  1404. oldIsAnonymous = user.isAnonymous;
  1405. newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  1406. isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  1407. updates = {
  1408. uid: coreAccount.localId,
  1409. displayName: coreAccount.displayName || null,
  1410. photoURL: coreAccount.photoUrl || null,
  1411. email: coreAccount.email || null,
  1412. emailVerified: coreAccount.emailVerified || false,
  1413. phoneNumber: coreAccount.phoneNumber || null,
  1414. tenantId: coreAccount.tenantId || null,
  1415. providerData: providerData,
  1416. metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
  1417. isAnonymous: isAnonymous
  1418. };
  1419. Object.assign(user, updates);
  1420. return [2 /*return*/];
  1421. }
  1422. });
  1423. });
  1424. }
  1425. /**
  1426. * Reloads user account data, if signed in.
  1427. *
  1428. * @param user - The user.
  1429. *
  1430. * @public
  1431. */
  1432. function reload(user) {
  1433. return tslib.__awaiter(this, void 0, void 0, function () {
  1434. var userInternal;
  1435. return tslib.__generator(this, function (_a) {
  1436. switch (_a.label) {
  1437. case 0:
  1438. userInternal = util.getModularInstance(user);
  1439. return [4 /*yield*/, _reloadWithoutSaving(userInternal)];
  1440. case 1:
  1441. _a.sent();
  1442. // Even though the current user hasn't changed, update
  1443. // current user will trigger a persistence update w/ the
  1444. // new info.
  1445. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  1446. case 2:
  1447. // Even though the current user hasn't changed, update
  1448. // current user will trigger a persistence update w/ the
  1449. // new info.
  1450. _a.sent();
  1451. userInternal.auth._notifyListenersIfCurrent(userInternal);
  1452. return [2 /*return*/];
  1453. }
  1454. });
  1455. });
  1456. }
  1457. function mergeProviderData(original, newData) {
  1458. var deduped = original.filter(function (o) { return !newData.some(function (n) { return n.providerId === o.providerId; }); });
  1459. return tslib.__spreadArray(tslib.__spreadArray([], deduped, true), newData, true);
  1460. }
  1461. function extractProviderData(providers) {
  1462. return providers.map(function (_a) {
  1463. var providerId = _a.providerId, provider = tslib.__rest(_a, ["providerId"]);
  1464. return {
  1465. providerId: providerId,
  1466. uid: provider.rawId || '',
  1467. displayName: provider.displayName || null,
  1468. email: provider.email || null,
  1469. phoneNumber: provider.phoneNumber || null,
  1470. photoURL: provider.photoUrl || null
  1471. };
  1472. });
  1473. }
  1474. /**
  1475. * @license
  1476. * Copyright 2020 Google LLC
  1477. *
  1478. * Licensed under the Apache License, Version 2.0 (the "License");
  1479. * you may not use this file except in compliance with the License.
  1480. * You may obtain a copy of the License at
  1481. *
  1482. * http://www.apache.org/licenses/LICENSE-2.0
  1483. *
  1484. * Unless required by applicable law or agreed to in writing, software
  1485. * distributed under the License is distributed on an "AS IS" BASIS,
  1486. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1487. * See the License for the specific language governing permissions and
  1488. * limitations under the License.
  1489. */
  1490. function requestStsToken(auth, refreshToken) {
  1491. return tslib.__awaiter(this, void 0, void 0, function () {
  1492. var response;
  1493. var _this = this;
  1494. return tslib.__generator(this, function (_a) {
  1495. switch (_a.label) {
  1496. case 0: return [4 /*yield*/, _performFetchWithErrorHandling(auth, {}, function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  1497. var body, _a, tokenApiHost, apiKey, url, headers;
  1498. return tslib.__generator(this, function (_b) {
  1499. switch (_b.label) {
  1500. case 0:
  1501. body = util.querystring({
  1502. 'grant_type': 'refresh_token',
  1503. 'refresh_token': refreshToken
  1504. }).slice(1);
  1505. _a = auth.config, tokenApiHost = _a.tokenApiHost, apiKey = _a.apiKey;
  1506. url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* Endpoint.TOKEN */, "key=".concat(apiKey));
  1507. return [4 /*yield*/, auth._getAdditionalHeaders()];
  1508. case 1:
  1509. headers = _b.sent();
  1510. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
  1511. return [2 /*return*/, FetchProvider.fetch()(url, {
  1512. method: "POST" /* HttpMethod.POST */,
  1513. headers: headers,
  1514. body: body
  1515. })];
  1516. }
  1517. });
  1518. }); })];
  1519. case 1:
  1520. response = _a.sent();
  1521. // The response comes back in snake_case. Convert to camel:
  1522. return [2 /*return*/, {
  1523. accessToken: response.access_token,
  1524. expiresIn: response.expires_in,
  1525. refreshToken: response.refresh_token
  1526. }];
  1527. }
  1528. });
  1529. });
  1530. }
  1531. /**
  1532. * @license
  1533. * Copyright 2020 Google LLC
  1534. *
  1535. * Licensed under the Apache License, Version 2.0 (the "License");
  1536. * you may not use this file except in compliance with the License.
  1537. * You may obtain a copy of the License at
  1538. *
  1539. * http://www.apache.org/licenses/LICENSE-2.0
  1540. *
  1541. * Unless required by applicable law or agreed to in writing, software
  1542. * distributed under the License is distributed on an "AS IS" BASIS,
  1543. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1544. * See the License for the specific language governing permissions and
  1545. * limitations under the License.
  1546. */
  1547. /**
  1548. * We need to mark this class as internal explicitly to exclude it in the public typings, because
  1549. * it references AuthInternal which has a circular dependency with UserInternal.
  1550. *
  1551. * @internal
  1552. */
  1553. var StsTokenManager = /** @class */ (function () {
  1554. function StsTokenManager() {
  1555. this.refreshToken = null;
  1556. this.accessToken = null;
  1557. this.expirationTime = null;
  1558. }
  1559. Object.defineProperty(StsTokenManager.prototype, "isExpired", {
  1560. get: function () {
  1561. return (!this.expirationTime ||
  1562. Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);
  1563. },
  1564. enumerable: false,
  1565. configurable: true
  1566. });
  1567. StsTokenManager.prototype.updateFromServerResponse = function (response) {
  1568. _assert(response.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1569. _assert(typeof response.idToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1570. _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1571. var expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
  1572. ? Number(response.expiresIn)
  1573. : _tokenExpiresIn(response.idToken);
  1574. this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  1575. };
  1576. StsTokenManager.prototype.getToken = function (auth, forceRefresh) {
  1577. if (forceRefresh === void 0) { forceRefresh = false; }
  1578. return tslib.__awaiter(this, void 0, void 0, function () {
  1579. return tslib.__generator(this, function (_a) {
  1580. switch (_a.label) {
  1581. case 0:
  1582. _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */);
  1583. if (!forceRefresh && this.accessToken && !this.isExpired) {
  1584. return [2 /*return*/, this.accessToken];
  1585. }
  1586. if (!this.refreshToken) return [3 /*break*/, 2];
  1587. return [4 /*yield*/, this.refresh(auth, this.refreshToken)];
  1588. case 1:
  1589. _a.sent();
  1590. return [2 /*return*/, this.accessToken];
  1591. case 2: return [2 /*return*/, null];
  1592. }
  1593. });
  1594. });
  1595. };
  1596. StsTokenManager.prototype.clearRefreshToken = function () {
  1597. this.refreshToken = null;
  1598. };
  1599. StsTokenManager.prototype.refresh = function (auth, oldToken) {
  1600. return tslib.__awaiter(this, void 0, void 0, function () {
  1601. var _a, accessToken, refreshToken, expiresIn;
  1602. return tslib.__generator(this, function (_b) {
  1603. switch (_b.label) {
  1604. case 0: return [4 /*yield*/, requestStsToken(auth, oldToken)];
  1605. case 1:
  1606. _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken, expiresIn = _a.expiresIn;
  1607. this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  1608. return [2 /*return*/];
  1609. }
  1610. });
  1611. });
  1612. };
  1613. StsTokenManager.prototype.updateTokensAndExpiration = function (accessToken, refreshToken, expiresInSec) {
  1614. this.refreshToken = refreshToken || null;
  1615. this.accessToken = accessToken || null;
  1616. this.expirationTime = Date.now() + expiresInSec * 1000;
  1617. };
  1618. StsTokenManager.fromJSON = function (appName, object) {
  1619. var refreshToken = object.refreshToken, accessToken = object.accessToken, expirationTime = object.expirationTime;
  1620. var manager = new StsTokenManager();
  1621. if (refreshToken) {
  1622. _assert(typeof refreshToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1623. appName: appName
  1624. });
  1625. manager.refreshToken = refreshToken;
  1626. }
  1627. if (accessToken) {
  1628. _assert(typeof accessToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1629. appName: appName
  1630. });
  1631. manager.accessToken = accessToken;
  1632. }
  1633. if (expirationTime) {
  1634. _assert(typeof expirationTime === 'number', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1635. appName: appName
  1636. });
  1637. manager.expirationTime = expirationTime;
  1638. }
  1639. return manager;
  1640. };
  1641. StsTokenManager.prototype.toJSON = function () {
  1642. return {
  1643. refreshToken: this.refreshToken,
  1644. accessToken: this.accessToken,
  1645. expirationTime: this.expirationTime
  1646. };
  1647. };
  1648. StsTokenManager.prototype._assign = function (stsTokenManager) {
  1649. this.accessToken = stsTokenManager.accessToken;
  1650. this.refreshToken = stsTokenManager.refreshToken;
  1651. this.expirationTime = stsTokenManager.expirationTime;
  1652. };
  1653. StsTokenManager.prototype._clone = function () {
  1654. return Object.assign(new StsTokenManager(), this.toJSON());
  1655. };
  1656. StsTokenManager.prototype._performRefresh = function () {
  1657. return debugFail('not implemented');
  1658. };
  1659. return StsTokenManager;
  1660. }());
  1661. /**
  1662. * @license
  1663. * Copyright 2020 Google LLC
  1664. *
  1665. * Licensed under the Apache License, Version 2.0 (the "License");
  1666. * you may not use this file except in compliance with the License.
  1667. * You may obtain a copy of the License at
  1668. *
  1669. * http://www.apache.org/licenses/LICENSE-2.0
  1670. *
  1671. * Unless required by applicable law or agreed to in writing, software
  1672. * distributed under the License is distributed on an "AS IS" BASIS,
  1673. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1674. * See the License for the specific language governing permissions and
  1675. * limitations under the License.
  1676. */
  1677. function assertStringOrUndefined(assertion, appName) {
  1678. _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, { appName: appName });
  1679. }
  1680. var UserImpl = /** @class */ (function () {
  1681. function UserImpl(_a) {
  1682. var uid = _a.uid, auth = _a.auth, stsTokenManager = _a.stsTokenManager, opt = tslib.__rest(_a, ["uid", "auth", "stsTokenManager"]);
  1683. // For the user object, provider is always Firebase.
  1684. this.providerId = "firebase" /* ProviderId.FIREBASE */;
  1685. this.proactiveRefresh = new ProactiveRefresh(this);
  1686. this.reloadUserInfo = null;
  1687. this.reloadListener = null;
  1688. this.uid = uid;
  1689. this.auth = auth;
  1690. this.stsTokenManager = stsTokenManager;
  1691. this.accessToken = stsTokenManager.accessToken;
  1692. this.displayName = opt.displayName || null;
  1693. this.email = opt.email || null;
  1694. this.emailVerified = opt.emailVerified || false;
  1695. this.phoneNumber = opt.phoneNumber || null;
  1696. this.photoURL = opt.photoURL || null;
  1697. this.isAnonymous = opt.isAnonymous || false;
  1698. this.tenantId = opt.tenantId || null;
  1699. this.providerData = opt.providerData ? tslib.__spreadArray([], opt.providerData, true) : [];
  1700. this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
  1701. }
  1702. UserImpl.prototype.getIdToken = function (forceRefresh) {
  1703. return tslib.__awaiter(this, void 0, void 0, function () {
  1704. var accessToken;
  1705. return tslib.__generator(this, function (_a) {
  1706. switch (_a.label) {
  1707. case 0: return [4 /*yield*/, _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh))];
  1708. case 1:
  1709. accessToken = _a.sent();
  1710. _assert(accessToken, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1711. if (!(this.accessToken !== accessToken)) return [3 /*break*/, 3];
  1712. this.accessToken = accessToken;
  1713. return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1714. case 2:
  1715. _a.sent();
  1716. this.auth._notifyListenersIfCurrent(this);
  1717. _a.label = 3;
  1718. case 3: return [2 /*return*/, accessToken];
  1719. }
  1720. });
  1721. });
  1722. };
  1723. UserImpl.prototype.getIdTokenResult = function (forceRefresh) {
  1724. return getIdTokenResult(this, forceRefresh);
  1725. };
  1726. UserImpl.prototype.reload = function () {
  1727. return reload(this);
  1728. };
  1729. UserImpl.prototype._assign = function (user) {
  1730. if (this === user) {
  1731. return;
  1732. }
  1733. _assert(this.uid === user.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1734. this.displayName = user.displayName;
  1735. this.photoURL = user.photoURL;
  1736. this.email = user.email;
  1737. this.emailVerified = user.emailVerified;
  1738. this.phoneNumber = user.phoneNumber;
  1739. this.isAnonymous = user.isAnonymous;
  1740. this.tenantId = user.tenantId;
  1741. this.providerData = user.providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); });
  1742. this.metadata._copy(user.metadata);
  1743. this.stsTokenManager._assign(user.stsTokenManager);
  1744. };
  1745. UserImpl.prototype._clone = function (auth) {
  1746. return new UserImpl(tslib.__assign(tslib.__assign({}, this), { auth: auth, stsTokenManager: this.stsTokenManager._clone() }));
  1747. };
  1748. UserImpl.prototype._onReload = function (callback) {
  1749. // There should only ever be one listener, and that is a single instance of MultiFactorUser
  1750. _assert(!this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1751. this.reloadListener = callback;
  1752. if (this.reloadUserInfo) {
  1753. this._notifyReloadListener(this.reloadUserInfo);
  1754. this.reloadUserInfo = null;
  1755. }
  1756. };
  1757. UserImpl.prototype._notifyReloadListener = function (userInfo) {
  1758. if (this.reloadListener) {
  1759. this.reloadListener(userInfo);
  1760. }
  1761. else {
  1762. // If no listener is subscribed yet, save the result so it's available when they do subscribe
  1763. this.reloadUserInfo = userInfo;
  1764. }
  1765. };
  1766. UserImpl.prototype._startProactiveRefresh = function () {
  1767. this.proactiveRefresh._start();
  1768. };
  1769. UserImpl.prototype._stopProactiveRefresh = function () {
  1770. this.proactiveRefresh._stop();
  1771. };
  1772. UserImpl.prototype._updateTokensIfNecessary = function (response, reload) {
  1773. if (reload === void 0) { reload = false; }
  1774. return tslib.__awaiter(this, void 0, void 0, function () {
  1775. var tokensRefreshed;
  1776. return tslib.__generator(this, function (_a) {
  1777. switch (_a.label) {
  1778. case 0:
  1779. tokensRefreshed = false;
  1780. if (response.idToken &&
  1781. response.idToken !== this.stsTokenManager.accessToken) {
  1782. this.stsTokenManager.updateFromServerResponse(response);
  1783. tokensRefreshed = true;
  1784. }
  1785. if (!reload) return [3 /*break*/, 2];
  1786. return [4 /*yield*/, _reloadWithoutSaving(this)];
  1787. case 1:
  1788. _a.sent();
  1789. _a.label = 2;
  1790. case 2: return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1791. case 3:
  1792. _a.sent();
  1793. if (tokensRefreshed) {
  1794. this.auth._notifyListenersIfCurrent(this);
  1795. }
  1796. return [2 /*return*/];
  1797. }
  1798. });
  1799. });
  1800. };
  1801. UserImpl.prototype.delete = function () {
  1802. return tslib.__awaiter(this, void 0, void 0, function () {
  1803. var idToken;
  1804. return tslib.__generator(this, function (_a) {
  1805. switch (_a.label) {
  1806. case 0: return [4 /*yield*/, this.getIdToken()];
  1807. case 1:
  1808. idToken = _a.sent();
  1809. return [4 /*yield*/, _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken: idToken }))];
  1810. case 2:
  1811. _a.sent();
  1812. this.stsTokenManager.clearRefreshToken();
  1813. // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
  1814. // cancels pending actions...
  1815. return [2 /*return*/, this.auth.signOut()];
  1816. }
  1817. });
  1818. });
  1819. };
  1820. UserImpl.prototype.toJSON = function () {
  1821. return tslib.__assign(tslib.__assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); }), stsTokenManager: this.stsTokenManager.toJSON(),
  1822. // Redirect event ID must be maintained in case there is a pending
  1823. // redirect event.
  1824. _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
  1825. // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
  1826. apiKey: this.auth.config.apiKey, appName: this.auth.name });
  1827. };
  1828. Object.defineProperty(UserImpl.prototype, "refreshToken", {
  1829. get: function () {
  1830. return this.stsTokenManager.refreshToken || '';
  1831. },
  1832. enumerable: false,
  1833. configurable: true
  1834. });
  1835. UserImpl._fromJSON = function (auth, object) {
  1836. var _a, _b, _c, _d, _e, _f, _g, _h;
  1837. var displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
  1838. var email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
  1839. var phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
  1840. var photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
  1841. var tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
  1842. var _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
  1843. var createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
  1844. var lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
  1845. var uid = object.uid, emailVerified = object.emailVerified, isAnonymous = object.isAnonymous, providerData = object.providerData, plainObjectTokenManager = object.stsTokenManager;
  1846. _assert(uid && plainObjectTokenManager, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1847. var stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
  1848. _assert(typeof uid === 'string', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1849. assertStringOrUndefined(displayName, auth.name);
  1850. assertStringOrUndefined(email, auth.name);
  1851. _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1852. _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1853. assertStringOrUndefined(phoneNumber, auth.name);
  1854. assertStringOrUndefined(photoURL, auth.name);
  1855. assertStringOrUndefined(tenantId, auth.name);
  1856. assertStringOrUndefined(_redirectEventId, auth.name);
  1857. assertStringOrUndefined(createdAt, auth.name);
  1858. assertStringOrUndefined(lastLoginAt, auth.name);
  1859. var user = new UserImpl({
  1860. uid: uid,
  1861. auth: auth,
  1862. email: email,
  1863. emailVerified: emailVerified,
  1864. displayName: displayName,
  1865. isAnonymous: isAnonymous,
  1866. photoURL: photoURL,
  1867. phoneNumber: phoneNumber,
  1868. tenantId: tenantId,
  1869. stsTokenManager: stsTokenManager,
  1870. createdAt: createdAt,
  1871. lastLoginAt: lastLoginAt
  1872. });
  1873. if (providerData && Array.isArray(providerData)) {
  1874. user.providerData = providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); });
  1875. }
  1876. if (_redirectEventId) {
  1877. user._redirectEventId = _redirectEventId;
  1878. }
  1879. return user;
  1880. };
  1881. /**
  1882. * Initialize a User from an idToken server response
  1883. * @param auth
  1884. * @param idTokenResponse
  1885. */
  1886. UserImpl._fromIdTokenResponse = function (auth, idTokenResponse, isAnonymous) {
  1887. if (isAnonymous === void 0) { isAnonymous = false; }
  1888. return tslib.__awaiter(this, void 0, void 0, function () {
  1889. var stsTokenManager, user;
  1890. return tslib.__generator(this, function (_a) {
  1891. switch (_a.label) {
  1892. case 0:
  1893. stsTokenManager = new StsTokenManager();
  1894. stsTokenManager.updateFromServerResponse(idTokenResponse);
  1895. user = new UserImpl({
  1896. uid: idTokenResponse.localId,
  1897. auth: auth,
  1898. stsTokenManager: stsTokenManager,
  1899. isAnonymous: isAnonymous
  1900. });
  1901. // Updates the user info and data and resolves with a user instance.
  1902. return [4 /*yield*/, _reloadWithoutSaving(user)];
  1903. case 1:
  1904. // Updates the user info and data and resolves with a user instance.
  1905. _a.sent();
  1906. return [2 /*return*/, user];
  1907. }
  1908. });
  1909. });
  1910. };
  1911. return UserImpl;
  1912. }());
  1913. /**
  1914. * @license
  1915. * Copyright 2019 Google LLC
  1916. *
  1917. * Licensed under the Apache License, Version 2.0 (the "License");
  1918. * you may not use this file except in compliance with the License.
  1919. * You may obtain a copy of the License at
  1920. *
  1921. * http://www.apache.org/licenses/LICENSE-2.0
  1922. *
  1923. * Unless required by applicable law or agreed to in writing, software
  1924. * distributed under the License is distributed on an "AS IS" BASIS,
  1925. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1926. * See the License for the specific language governing permissions and
  1927. * limitations under the License.
  1928. */
  1929. var InMemoryPersistence = /** @class */ (function () {
  1930. function InMemoryPersistence() {
  1931. this.type = "NONE" /* PersistenceType.NONE */;
  1932. this.storage = {};
  1933. }
  1934. InMemoryPersistence.prototype._isAvailable = function () {
  1935. return tslib.__awaiter(this, void 0, void 0, function () {
  1936. return tslib.__generator(this, function (_a) {
  1937. return [2 /*return*/, true];
  1938. });
  1939. });
  1940. };
  1941. InMemoryPersistence.prototype._set = function (key, value) {
  1942. return tslib.__awaiter(this, void 0, void 0, function () {
  1943. return tslib.__generator(this, function (_a) {
  1944. this.storage[key] = value;
  1945. return [2 /*return*/];
  1946. });
  1947. });
  1948. };
  1949. InMemoryPersistence.prototype._get = function (key) {
  1950. return tslib.__awaiter(this, void 0, void 0, function () {
  1951. var value;
  1952. return tslib.__generator(this, function (_a) {
  1953. value = this.storage[key];
  1954. return [2 /*return*/, value === undefined ? null : value];
  1955. });
  1956. });
  1957. };
  1958. InMemoryPersistence.prototype._remove = function (key) {
  1959. return tslib.__awaiter(this, void 0, void 0, function () {
  1960. return tslib.__generator(this, function (_a) {
  1961. delete this.storage[key];
  1962. return [2 /*return*/];
  1963. });
  1964. });
  1965. };
  1966. InMemoryPersistence.prototype._addListener = function (_key, _listener) {
  1967. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  1968. return;
  1969. };
  1970. InMemoryPersistence.prototype._removeListener = function (_key, _listener) {
  1971. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  1972. return;
  1973. };
  1974. InMemoryPersistence.type = 'NONE';
  1975. return InMemoryPersistence;
  1976. }());
  1977. /**
  1978. * An implementation of {@link Persistence} of type 'NONE'.
  1979. *
  1980. * @public
  1981. */
  1982. var inMemoryPersistence = InMemoryPersistence;
  1983. /**
  1984. * @license
  1985. * Copyright 2019 Google LLC
  1986. *
  1987. * Licensed under the Apache License, Version 2.0 (the "License");
  1988. * you may not use this file except in compliance with the License.
  1989. * You may obtain a copy of the License at
  1990. *
  1991. * http://www.apache.org/licenses/LICENSE-2.0
  1992. *
  1993. * Unless required by applicable law or agreed to in writing, software
  1994. * distributed under the License is distributed on an "AS IS" BASIS,
  1995. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1996. * See the License for the specific language governing permissions and
  1997. * limitations under the License.
  1998. */
  1999. function _persistenceKeyName(key, apiKey, appName) {
  2000. return "".concat("firebase" /* Namespace.PERSISTENCE */, ":").concat(key, ":").concat(apiKey, ":").concat(appName);
  2001. }
  2002. var PersistenceUserManager = /** @class */ (function () {
  2003. function PersistenceUserManager(persistence, auth, userKey) {
  2004. this.persistence = persistence;
  2005. this.auth = auth;
  2006. this.userKey = userKey;
  2007. var _a = this.auth, config = _a.config, name = _a.name;
  2008. this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
  2009. this.fullPersistenceKey = _persistenceKeyName("persistence" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);
  2010. this.boundEventHandler = auth._onStorageEvent.bind(auth);
  2011. this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  2012. }
  2013. PersistenceUserManager.prototype.setCurrentUser = function (user) {
  2014. return this.persistence._set(this.fullUserKey, user.toJSON());
  2015. };
  2016. PersistenceUserManager.prototype.getCurrentUser = function () {
  2017. return tslib.__awaiter(this, void 0, void 0, function () {
  2018. var blob;
  2019. return tslib.__generator(this, function (_a) {
  2020. switch (_a.label) {
  2021. case 0: return [4 /*yield*/, this.persistence._get(this.fullUserKey)];
  2022. case 1:
  2023. blob = _a.sent();
  2024. return [2 /*return*/, blob ? UserImpl._fromJSON(this.auth, blob) : null];
  2025. }
  2026. });
  2027. });
  2028. };
  2029. PersistenceUserManager.prototype.removeCurrentUser = function () {
  2030. return this.persistence._remove(this.fullUserKey);
  2031. };
  2032. PersistenceUserManager.prototype.savePersistenceForRedirect = function () {
  2033. return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  2034. };
  2035. PersistenceUserManager.prototype.setPersistence = function (newPersistence) {
  2036. return tslib.__awaiter(this, void 0, void 0, function () {
  2037. var currentUser;
  2038. return tslib.__generator(this, function (_a) {
  2039. switch (_a.label) {
  2040. case 0:
  2041. if (this.persistence === newPersistence) {
  2042. return [2 /*return*/];
  2043. }
  2044. return [4 /*yield*/, this.getCurrentUser()];
  2045. case 1:
  2046. currentUser = _a.sent();
  2047. return [4 /*yield*/, this.removeCurrentUser()];
  2048. case 2:
  2049. _a.sent();
  2050. this.persistence = newPersistence;
  2051. if (currentUser) {
  2052. return [2 /*return*/, this.setCurrentUser(currentUser)];
  2053. }
  2054. return [2 /*return*/];
  2055. }
  2056. });
  2057. });
  2058. };
  2059. PersistenceUserManager.prototype.delete = function () {
  2060. this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  2061. };
  2062. PersistenceUserManager.create = function (auth, persistenceHierarchy, userKey) {
  2063. if (userKey === void 0) { userKey = "authUser" /* KeyName.AUTH_USER */; }
  2064. return tslib.__awaiter(this, void 0, void 0, function () {
  2065. var availablePersistences, selectedPersistence, key, userToMigrate, _i, persistenceHierarchy_1, persistence, blob, user, migrationHierarchy;
  2066. var _this = this;
  2067. return tslib.__generator(this, function (_b) {
  2068. switch (_b.label) {
  2069. case 0:
  2070. if (!persistenceHierarchy.length) {
  2071. return [2 /*return*/, new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey)];
  2072. }
  2073. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return tslib.__awaiter(_this, void 0, void 0, function () {
  2074. return tslib.__generator(this, function (_a) {
  2075. switch (_a.label) {
  2076. case 0: return [4 /*yield*/, persistence._isAvailable()];
  2077. case 1:
  2078. if (_a.sent()) {
  2079. return [2 /*return*/, persistence];
  2080. }
  2081. return [2 /*return*/, undefined];
  2082. }
  2083. });
  2084. }); }))];
  2085. case 1:
  2086. availablePersistences = (_b.sent()).filter(function (persistence) { return persistence; });
  2087. selectedPersistence = availablePersistences[0] ||
  2088. _getInstance(inMemoryPersistence);
  2089. key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
  2090. userToMigrate = null;
  2091. _i = 0, persistenceHierarchy_1 = persistenceHierarchy;
  2092. _b.label = 2;
  2093. case 2:
  2094. if (!(_i < persistenceHierarchy_1.length)) return [3 /*break*/, 7];
  2095. persistence = persistenceHierarchy_1[_i];
  2096. _b.label = 3;
  2097. case 3:
  2098. _b.trys.push([3, 5, , 6]);
  2099. return [4 /*yield*/, persistence._get(key)];
  2100. case 4:
  2101. blob = _b.sent();
  2102. if (blob) {
  2103. user = UserImpl._fromJSON(auth, blob);
  2104. if (persistence !== selectedPersistence) {
  2105. userToMigrate = user;
  2106. }
  2107. selectedPersistence = persistence;
  2108. return [3 /*break*/, 7];
  2109. }
  2110. return [3 /*break*/, 6];
  2111. case 5:
  2112. _b.sent();
  2113. return [3 /*break*/, 6];
  2114. case 6:
  2115. _i++;
  2116. return [3 /*break*/, 2];
  2117. case 7:
  2118. migrationHierarchy = availablePersistences.filter(function (p) { return p._shouldAllowMigration; });
  2119. // If the persistence does _not_ allow migration, just finish off here
  2120. if (!selectedPersistence._shouldAllowMigration ||
  2121. !migrationHierarchy.length) {
  2122. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2123. }
  2124. selectedPersistence = migrationHierarchy[0];
  2125. if (!userToMigrate) return [3 /*break*/, 9];
  2126. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2127. // we'll just let it bubble to surface the error.
  2128. return [4 /*yield*/, selectedPersistence._set(key, userToMigrate.toJSON())];
  2129. case 8:
  2130. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2131. // we'll just let it bubble to surface the error.
  2132. _b.sent();
  2133. _b.label = 9;
  2134. case 9:
  2135. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2136. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2137. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return tslib.__awaiter(_this, void 0, void 0, function () {
  2138. return tslib.__generator(this, function (_b) {
  2139. switch (_b.label) {
  2140. case 0:
  2141. if (!(persistence !== selectedPersistence)) return [3 /*break*/, 4];
  2142. _b.label = 1;
  2143. case 1:
  2144. _b.trys.push([1, 3, , 4]);
  2145. return [4 /*yield*/, persistence._remove(key)];
  2146. case 2:
  2147. _b.sent();
  2148. return [3 /*break*/, 4];
  2149. case 3:
  2150. _b.sent();
  2151. return [3 /*break*/, 4];
  2152. case 4: return [2 /*return*/];
  2153. }
  2154. });
  2155. }); }))];
  2156. case 10:
  2157. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2158. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2159. _b.sent();
  2160. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2161. }
  2162. });
  2163. });
  2164. };
  2165. return PersistenceUserManager;
  2166. }());
  2167. /**
  2168. * @license
  2169. * Copyright 2020 Google LLC
  2170. *
  2171. * Licensed under the Apache License, Version 2.0 (the "License");
  2172. * you may not use this file except in compliance with the License.
  2173. * You may obtain a copy of the License at
  2174. *
  2175. * http://www.apache.org/licenses/LICENSE-2.0
  2176. *
  2177. * Unless required by applicable law or agreed to in writing, software
  2178. * distributed under the License is distributed on an "AS IS" BASIS,
  2179. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2180. * See the License for the specific language governing permissions and
  2181. * limitations under the License.
  2182. */
  2183. /**
  2184. * Determine the browser for the purposes of reporting usage to the API
  2185. */
  2186. function _getBrowserName(userAgent) {
  2187. var ua = userAgent.toLowerCase();
  2188. if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
  2189. return "Opera" /* BrowserName.OPERA */;
  2190. }
  2191. else if (_isIEMobile(ua)) {
  2192. // Windows phone IEMobile browser.
  2193. return "IEMobile" /* BrowserName.IEMOBILE */;
  2194. }
  2195. else if (ua.includes('msie') || ua.includes('trident/')) {
  2196. return "IE" /* BrowserName.IE */;
  2197. }
  2198. else if (ua.includes('edge/')) {
  2199. return "Edge" /* BrowserName.EDGE */;
  2200. }
  2201. else if (_isFirefox(ua)) {
  2202. return "Firefox" /* BrowserName.FIREFOX */;
  2203. }
  2204. else if (ua.includes('silk/')) {
  2205. return "Silk" /* BrowserName.SILK */;
  2206. }
  2207. else if (_isBlackBerry(ua)) {
  2208. // Blackberry browser.
  2209. return "Blackberry" /* BrowserName.BLACKBERRY */;
  2210. }
  2211. else if (_isWebOS(ua)) {
  2212. // WebOS default browser.
  2213. return "Webos" /* BrowserName.WEBOS */;
  2214. }
  2215. else if (_isSafari(ua)) {
  2216. return "Safari" /* BrowserName.SAFARI */;
  2217. }
  2218. else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
  2219. !ua.includes('edge/')) {
  2220. return "Chrome" /* BrowserName.CHROME */;
  2221. }
  2222. else if (_isAndroid(ua)) {
  2223. // Android stock browser.
  2224. return "Android" /* BrowserName.ANDROID */;
  2225. }
  2226. else {
  2227. // Most modern browsers have name/version at end of user agent string.
  2228. var re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
  2229. var matches = userAgent.match(re);
  2230. if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
  2231. return matches[1];
  2232. }
  2233. }
  2234. return "Other" /* BrowserName.OTHER */;
  2235. }
  2236. function _isFirefox(ua) {
  2237. if (ua === void 0) { ua = util.getUA(); }
  2238. return /firefox\//i.test(ua);
  2239. }
  2240. function _isSafari(userAgent) {
  2241. if (userAgent === void 0) { userAgent = util.getUA(); }
  2242. var ua = userAgent.toLowerCase();
  2243. return (ua.includes('safari/') &&
  2244. !ua.includes('chrome/') &&
  2245. !ua.includes('crios/') &&
  2246. !ua.includes('android'));
  2247. }
  2248. function _isChromeIOS(ua) {
  2249. if (ua === void 0) { ua = util.getUA(); }
  2250. return /crios\//i.test(ua);
  2251. }
  2252. function _isIEMobile(ua) {
  2253. if (ua === void 0) { ua = util.getUA(); }
  2254. return /iemobile/i.test(ua);
  2255. }
  2256. function _isAndroid(ua) {
  2257. if (ua === void 0) { ua = util.getUA(); }
  2258. return /android/i.test(ua);
  2259. }
  2260. function _isBlackBerry(ua) {
  2261. if (ua === void 0) { ua = util.getUA(); }
  2262. return /blackberry/i.test(ua);
  2263. }
  2264. function _isWebOS(ua) {
  2265. if (ua === void 0) { ua = util.getUA(); }
  2266. return /webos/i.test(ua);
  2267. }
  2268. function _isIOS(ua) {
  2269. if (ua === void 0) { ua = util.getUA(); }
  2270. return (/iphone|ipad|ipod/i.test(ua) ||
  2271. (/macintosh/i.test(ua) && /mobile/i.test(ua)));
  2272. }
  2273. function _isIOS7Or8(ua) {
  2274. if (ua === void 0) { ua = util.getUA(); }
  2275. return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
  2276. /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
  2277. }
  2278. function _isIOSStandalone(ua) {
  2279. var _a;
  2280. if (ua === void 0) { ua = util.getUA(); }
  2281. return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);
  2282. }
  2283. function _isIE10() {
  2284. return util.isIE() && document.documentMode === 10;
  2285. }
  2286. function _isMobileBrowser(ua) {
  2287. if (ua === void 0) { ua = util.getUA(); }
  2288. // TODO: implement getBrowserName equivalent for OS.
  2289. return (_isIOS(ua) ||
  2290. _isAndroid(ua) ||
  2291. _isWebOS(ua) ||
  2292. _isBlackBerry(ua) ||
  2293. /windows phone/i.test(ua) ||
  2294. _isIEMobile(ua));
  2295. }
  2296. function _isIframe() {
  2297. try {
  2298. // Check that the current window is not the top window.
  2299. // If so, return true.
  2300. return !!(window && window !== window.top);
  2301. }
  2302. catch (e) {
  2303. return false;
  2304. }
  2305. }
  2306. /**
  2307. * @license
  2308. * Copyright 2020 Google LLC
  2309. *
  2310. * Licensed under the Apache License, Version 2.0 (the "License");
  2311. * you may not use this file except in compliance with the License.
  2312. * You may obtain a copy of the License at
  2313. *
  2314. * http://www.apache.org/licenses/LICENSE-2.0
  2315. *
  2316. * Unless required by applicable law or agreed to in writing, software
  2317. * distributed under the License is distributed on an "AS IS" BASIS,
  2318. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2319. * See the License for the specific language governing permissions and
  2320. * limitations under the License.
  2321. */
  2322. /*
  2323. * Determine the SDK version string
  2324. */
  2325. function _getClientVersion(clientPlatform, frameworks) {
  2326. if (frameworks === void 0) { frameworks = []; }
  2327. var reportedPlatform;
  2328. switch (clientPlatform) {
  2329. case "Browser" /* ClientPlatform.BROWSER */:
  2330. // In a browser environment, report the browser name.
  2331. reportedPlatform = _getBrowserName(util.getUA());
  2332. break;
  2333. case "Worker" /* ClientPlatform.WORKER */:
  2334. // Technically a worker runs from a browser but we need to differentiate a
  2335. // worker from a browser.
  2336. // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
  2337. reportedPlatform = "".concat(_getBrowserName(util.getUA()), "-").concat(clientPlatform);
  2338. break;
  2339. default:
  2340. reportedPlatform = clientPlatform;
  2341. }
  2342. var reportedFrameworks = frameworks.length
  2343. ? frameworks.join(',')
  2344. : 'FirebaseCore-web'; /* default value if no other framework is used */
  2345. return "".concat(reportedPlatform, "/").concat("JsCore" /* ClientImplementation.CORE */, "/").concat(app.SDK_VERSION, "/").concat(reportedFrameworks);
  2346. }
  2347. /**
  2348. * @license
  2349. * Copyright 2022 Google LLC
  2350. *
  2351. * Licensed under the Apache License, Version 2.0 (the "License");
  2352. * you may not use this file except in compliance with the License.
  2353. * You may obtain a copy of the License at
  2354. *
  2355. * http://www.apache.org/licenses/LICENSE-2.0
  2356. *
  2357. * Unless required by applicable law or agreed to in writing, software
  2358. * distributed under the License is distributed on an "AS IS" BASIS,
  2359. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2360. * See the License for the specific language governing permissions and
  2361. * limitations under the License.
  2362. */
  2363. var AuthMiddlewareQueue = /** @class */ (function () {
  2364. function AuthMiddlewareQueue(auth) {
  2365. this.auth = auth;
  2366. this.queue = [];
  2367. }
  2368. AuthMiddlewareQueue.prototype.pushCallback = function (callback, onAbort) {
  2369. var _this = this;
  2370. // The callback could be sync or async. Wrap it into a
  2371. // function that is always async.
  2372. var wrappedCallback = function (user) {
  2373. return new Promise(function (resolve, reject) {
  2374. try {
  2375. var result = callback(user);
  2376. // Either resolve with existing promise or wrap a non-promise
  2377. // return value into a promise.
  2378. resolve(result);
  2379. }
  2380. catch (e) {
  2381. // Sync callback throws.
  2382. reject(e);
  2383. }
  2384. });
  2385. };
  2386. // Attach the onAbort if present
  2387. wrappedCallback.onAbort = onAbort;
  2388. this.queue.push(wrappedCallback);
  2389. var index = this.queue.length - 1;
  2390. return function () {
  2391. // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
  2392. // indexing of other elements.
  2393. _this.queue[index] = function () { return Promise.resolve(); };
  2394. };
  2395. };
  2396. AuthMiddlewareQueue.prototype.runMiddleware = function (nextUser) {
  2397. return tslib.__awaiter(this, void 0, void 0, function () {
  2398. var onAbortStack, _i, _a, beforeStateCallback, e_1, _b, onAbortStack_1, onAbort;
  2399. return tslib.__generator(this, function (_c) {
  2400. switch (_c.label) {
  2401. case 0:
  2402. if (this.auth.currentUser === nextUser) {
  2403. return [2 /*return*/];
  2404. }
  2405. onAbortStack = [];
  2406. _c.label = 1;
  2407. case 1:
  2408. _c.trys.push([1, 6, , 7]);
  2409. _i = 0, _a = this.queue;
  2410. _c.label = 2;
  2411. case 2:
  2412. if (!(_i < _a.length)) return [3 /*break*/, 5];
  2413. beforeStateCallback = _a[_i];
  2414. return [4 /*yield*/, beforeStateCallback(nextUser)];
  2415. case 3:
  2416. _c.sent();
  2417. // Only push the onAbort if the callback succeeds
  2418. if (beforeStateCallback.onAbort) {
  2419. onAbortStack.push(beforeStateCallback.onAbort);
  2420. }
  2421. _c.label = 4;
  2422. case 4:
  2423. _i++;
  2424. return [3 /*break*/, 2];
  2425. case 5: return [3 /*break*/, 7];
  2426. case 6:
  2427. e_1 = _c.sent();
  2428. // Run all onAbort, with separate try/catch to ignore any errors and
  2429. // continue
  2430. onAbortStack.reverse();
  2431. for (_b = 0, onAbortStack_1 = onAbortStack; _b < onAbortStack_1.length; _b++) {
  2432. onAbort = onAbortStack_1[_b];
  2433. try {
  2434. onAbort();
  2435. }
  2436. catch (_) {
  2437. /* swallow error */
  2438. }
  2439. }
  2440. throw this.auth._errorFactory.create("login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */, {
  2441. originalMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message
  2442. });
  2443. case 7: return [2 /*return*/];
  2444. }
  2445. });
  2446. });
  2447. };
  2448. return AuthMiddlewareQueue;
  2449. }());
  2450. /**
  2451. * @license
  2452. * Copyright 2020 Google LLC
  2453. *
  2454. * Licensed under the Apache License, Version 2.0 (the "License");
  2455. * you may not use this file except in compliance with the License.
  2456. * You may obtain a copy of the License at
  2457. *
  2458. * http://www.apache.org/licenses/LICENSE-2.0
  2459. *
  2460. * Unless required by applicable law or agreed to in writing, software
  2461. * distributed under the License is distributed on an "AS IS" BASIS,
  2462. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2463. * See the License for the specific language governing permissions and
  2464. * limitations under the License.
  2465. */
  2466. var AuthImpl = /** @class */ (function () {
  2467. function AuthImpl(app, heartbeatServiceProvider, config) {
  2468. this.app = app;
  2469. this.heartbeatServiceProvider = heartbeatServiceProvider;
  2470. this.config = config;
  2471. this.currentUser = null;
  2472. this.emulatorConfig = null;
  2473. this.operations = Promise.resolve();
  2474. this.authStateSubscription = new Subscription(this);
  2475. this.idTokenSubscription = new Subscription(this);
  2476. this.beforeStateQueue = new AuthMiddlewareQueue(this);
  2477. this.redirectUser = null;
  2478. this.isProactiveRefreshEnabled = false;
  2479. // Any network calls will set this to true and prevent subsequent emulator
  2480. // initialization
  2481. this._canInitEmulator = true;
  2482. this._isInitialized = false;
  2483. this._deleted = false;
  2484. this._initializationPromise = null;
  2485. this._popupRedirectResolver = null;
  2486. this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
  2487. // Tracks the last notified UID for state change listeners to prevent
  2488. // repeated calls to the callbacks. Undefined means it's never been
  2489. // called, whereas null means it's been called with a signed out user
  2490. this.lastNotifiedUid = undefined;
  2491. this.languageCode = null;
  2492. this.tenantId = null;
  2493. this.settings = { appVerificationDisabledForTesting: false };
  2494. this.frameworks = [];
  2495. this.name = app.name;
  2496. this.clientVersion = config.sdkClientVersion;
  2497. }
  2498. AuthImpl.prototype._initializeWithPersistence = function (persistenceHierarchy, popupRedirectResolver) {
  2499. var _this = this;
  2500. if (popupRedirectResolver) {
  2501. this._popupRedirectResolver = _getInstance(popupRedirectResolver);
  2502. }
  2503. // Have to check for app deletion throughout initialization (after each
  2504. // promise resolution)
  2505. this._initializationPromise = this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  2506. var _a;
  2507. var _b, _c;
  2508. return tslib.__generator(this, function (_d) {
  2509. switch (_d.label) {
  2510. case 0:
  2511. if (this._deleted) {
  2512. return [2 /*return*/];
  2513. }
  2514. _a = this;
  2515. return [4 /*yield*/, PersistenceUserManager.create(this, persistenceHierarchy)];
  2516. case 1:
  2517. _a.persistenceManager = _d.sent();
  2518. if (this._deleted) {
  2519. return [2 /*return*/];
  2520. }
  2521. if (!((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively)) return [3 /*break*/, 5];
  2522. _d.label = 2;
  2523. case 2:
  2524. _d.trys.push([2, 4, , 5]);
  2525. return [4 /*yield*/, this._popupRedirectResolver._initialize(this)];
  2526. case 3:
  2527. _d.sent();
  2528. return [3 /*break*/, 5];
  2529. case 4:
  2530. _d.sent();
  2531. return [3 /*break*/, 5];
  2532. case 5: return [4 /*yield*/, this.initializeCurrentUser(popupRedirectResolver)];
  2533. case 6:
  2534. _d.sent();
  2535. this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
  2536. if (this._deleted) {
  2537. return [2 /*return*/];
  2538. }
  2539. this._isInitialized = true;
  2540. return [2 /*return*/];
  2541. }
  2542. });
  2543. }); });
  2544. return this._initializationPromise;
  2545. };
  2546. /**
  2547. * If the persistence is changed in another window, the user manager will let us know
  2548. */
  2549. AuthImpl.prototype._onStorageEvent = function () {
  2550. return tslib.__awaiter(this, void 0, void 0, function () {
  2551. var user;
  2552. return tslib.__generator(this, function (_a) {
  2553. switch (_a.label) {
  2554. case 0:
  2555. if (this._deleted) {
  2556. return [2 /*return*/];
  2557. }
  2558. return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2559. case 1:
  2560. user = _a.sent();
  2561. if (!this.currentUser && !user) {
  2562. // No change, do nothing (was signed out and remained signed out).
  2563. return [2 /*return*/];
  2564. }
  2565. if (!(this.currentUser && user && this.currentUser.uid === user.uid)) return [3 /*break*/, 3];
  2566. // Data update, simply copy data changes.
  2567. this._currentUser._assign(user);
  2568. // If tokens changed from previous user tokens, this will trigger
  2569. // notifyAuthListeners_.
  2570. return [4 /*yield*/, this.currentUser.getIdToken()];
  2571. case 2:
  2572. // If tokens changed from previous user tokens, this will trigger
  2573. // notifyAuthListeners_.
  2574. _a.sent();
  2575. return [2 /*return*/];
  2576. case 3:
  2577. // Update current Auth state. Either a new login or logout.
  2578. // Skip blocking callbacks, they should not apply to a change in another tab.
  2579. return [4 /*yield*/, this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true)];
  2580. case 4:
  2581. // Update current Auth state. Either a new login or logout.
  2582. // Skip blocking callbacks, they should not apply to a change in another tab.
  2583. _a.sent();
  2584. return [2 /*return*/];
  2585. }
  2586. });
  2587. });
  2588. };
  2589. AuthImpl.prototype.initializeCurrentUser = function (popupRedirectResolver) {
  2590. var _a;
  2591. return tslib.__awaiter(this, void 0, void 0, function () {
  2592. var previouslyStoredUser, futureCurrentUser, needsTocheckMiddleware, redirectUserEventId, storedUserEventId, result, e_2;
  2593. return tslib.__generator(this, function (_b) {
  2594. switch (_b.label) {
  2595. case 0: return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2596. case 1:
  2597. previouslyStoredUser = (_b.sent());
  2598. futureCurrentUser = previouslyStoredUser;
  2599. needsTocheckMiddleware = false;
  2600. if (!(popupRedirectResolver && this.config.authDomain)) return [3 /*break*/, 4];
  2601. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2602. case 2:
  2603. _b.sent();
  2604. redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
  2605. storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
  2606. return [4 /*yield*/, this.tryRedirectSignIn(popupRedirectResolver)];
  2607. case 3:
  2608. result = _b.sent();
  2609. // If the stored user (i.e. the old "currentUser") has a redirectId that
  2610. // matches the redirect user, then we want to initially sign in with the
  2611. // new user object from result.
  2612. // TODO(samgho): More thoroughly test all of this
  2613. if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
  2614. (result === null || result === void 0 ? void 0 : result.user)) {
  2615. futureCurrentUser = result.user;
  2616. needsTocheckMiddleware = true;
  2617. }
  2618. _b.label = 4;
  2619. case 4:
  2620. // If no user in persistence, there is no current user. Set to null.
  2621. if (!futureCurrentUser) {
  2622. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2623. }
  2624. if (!!futureCurrentUser._redirectEventId) return [3 /*break*/, 9];
  2625. if (!needsTocheckMiddleware) return [3 /*break*/, 8];
  2626. _b.label = 5;
  2627. case 5:
  2628. _b.trys.push([5, 7, , 8]);
  2629. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(futureCurrentUser)];
  2630. case 6:
  2631. _b.sent();
  2632. return [3 /*break*/, 8];
  2633. case 7:
  2634. e_2 = _b.sent();
  2635. futureCurrentUser = previouslyStoredUser;
  2636. // We know this is available since the bit is only set when the
  2637. // resolver is available
  2638. this._popupRedirectResolver._overrideRedirectResult(this, function () {
  2639. return Promise.reject(e_2);
  2640. });
  2641. return [3 /*break*/, 8];
  2642. case 8:
  2643. if (futureCurrentUser) {
  2644. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2645. }
  2646. else {
  2647. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2648. }
  2649. case 9:
  2650. _assert(this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2651. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2652. case 10:
  2653. _b.sent();
  2654. // If the redirect user's event ID matches the current user's event ID,
  2655. // DO NOT reload the current user, otherwise they'll be cleared from storage.
  2656. // This is important for the reauthenticateWithRedirect() flow.
  2657. if (this.redirectUser &&
  2658. this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
  2659. return [2 /*return*/, this.directlySetCurrentUser(futureCurrentUser)];
  2660. }
  2661. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2662. }
  2663. });
  2664. });
  2665. };
  2666. AuthImpl.prototype.tryRedirectSignIn = function (redirectResolver) {
  2667. return tslib.__awaiter(this, void 0, void 0, function () {
  2668. var result;
  2669. return tslib.__generator(this, function (_a) {
  2670. switch (_a.label) {
  2671. case 0:
  2672. result = null;
  2673. _a.label = 1;
  2674. case 1:
  2675. _a.trys.push([1, 3, , 5]);
  2676. return [4 /*yield*/, this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true)];
  2677. case 2:
  2678. // We know this._popupRedirectResolver is set since redirectResolver
  2679. // is passed in. The _completeRedirectFn expects the unwrapped extern.
  2680. result = _a.sent();
  2681. return [3 /*break*/, 5];
  2682. case 3:
  2683. _a.sent();
  2684. // Swallow any errors here; the code can retrieve them in
  2685. // getRedirectResult().
  2686. return [4 /*yield*/, this._setRedirectUser(null)];
  2687. case 4:
  2688. // Swallow any errors here; the code can retrieve them in
  2689. // getRedirectResult().
  2690. _a.sent();
  2691. return [3 /*break*/, 5];
  2692. case 5: return [2 /*return*/, result];
  2693. }
  2694. });
  2695. });
  2696. };
  2697. AuthImpl.prototype.reloadAndSetCurrentUserOrClear = function (user) {
  2698. return tslib.__awaiter(this, void 0, void 0, function () {
  2699. var e_4;
  2700. return tslib.__generator(this, function (_a) {
  2701. switch (_a.label) {
  2702. case 0:
  2703. _a.trys.push([0, 2, , 3]);
  2704. return [4 /*yield*/, _reloadWithoutSaving(user)];
  2705. case 1:
  2706. _a.sent();
  2707. return [3 /*break*/, 3];
  2708. case 2:
  2709. e_4 = _a.sent();
  2710. if ((e_4 === null || e_4 === void 0 ? void 0 : e_4.code) !==
  2711. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  2712. // Something's wrong with the user's token. Log them out and remove
  2713. // them from storage
  2714. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2715. }
  2716. return [3 /*break*/, 3];
  2717. case 3: return [2 /*return*/, this.directlySetCurrentUser(user)];
  2718. }
  2719. });
  2720. });
  2721. };
  2722. AuthImpl.prototype.useDeviceLanguage = function () {
  2723. this.languageCode = _getUserLanguage();
  2724. };
  2725. AuthImpl.prototype._delete = function () {
  2726. return tslib.__awaiter(this, void 0, void 0, function () {
  2727. return tslib.__generator(this, function (_a) {
  2728. this._deleted = true;
  2729. return [2 /*return*/];
  2730. });
  2731. });
  2732. };
  2733. AuthImpl.prototype.updateCurrentUser = function (userExtern) {
  2734. return tslib.__awaiter(this, void 0, void 0, function () {
  2735. var user;
  2736. return tslib.__generator(this, function (_a) {
  2737. user = userExtern
  2738. ? util.getModularInstance(userExtern)
  2739. : null;
  2740. if (user) {
  2741. _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */);
  2742. }
  2743. return [2 /*return*/, this._updateCurrentUser(user && user._clone(this))];
  2744. });
  2745. });
  2746. };
  2747. AuthImpl.prototype._updateCurrentUser = function (user, skipBeforeStateCallbacks) {
  2748. if (skipBeforeStateCallbacks === void 0) { skipBeforeStateCallbacks = false; }
  2749. return tslib.__awaiter(this, void 0, void 0, function () {
  2750. var _this = this;
  2751. return tslib.__generator(this, function (_a) {
  2752. switch (_a.label) {
  2753. case 0:
  2754. if (this._deleted) {
  2755. return [2 /*return*/];
  2756. }
  2757. if (user) {
  2758. _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  2759. }
  2760. if (!!skipBeforeStateCallbacks) return [3 /*break*/, 2];
  2761. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(user)];
  2762. case 1:
  2763. _a.sent();
  2764. _a.label = 2;
  2765. case 2: return [2 /*return*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  2766. return tslib.__generator(this, function (_a) {
  2767. switch (_a.label) {
  2768. case 0: return [4 /*yield*/, this.directlySetCurrentUser(user)];
  2769. case 1:
  2770. _a.sent();
  2771. this.notifyAuthListeners();
  2772. return [2 /*return*/];
  2773. }
  2774. });
  2775. }); })];
  2776. }
  2777. });
  2778. });
  2779. };
  2780. AuthImpl.prototype.signOut = function () {
  2781. return tslib.__awaiter(this, void 0, void 0, function () {
  2782. return tslib.__generator(this, function (_a) {
  2783. switch (_a.label) {
  2784. case 0:
  2785. // Run first, to block _setRedirectUser() if any callbacks fail.
  2786. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(null)];
  2787. case 1:
  2788. // Run first, to block _setRedirectUser() if any callbacks fail.
  2789. _a.sent();
  2790. if (!(this.redirectPersistenceManager || this._popupRedirectResolver)) return [3 /*break*/, 3];
  2791. return [4 /*yield*/, this._setRedirectUser(null)];
  2792. case 2:
  2793. _a.sent();
  2794. _a.label = 3;
  2795. case 3:
  2796. // Prevent callbacks from being called again in _updateCurrentUser, as
  2797. // they were already called in the first line.
  2798. return [2 /*return*/, this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true)];
  2799. }
  2800. });
  2801. });
  2802. };
  2803. AuthImpl.prototype.setPersistence = function (persistence) {
  2804. var _this = this;
  2805. return this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  2806. return tslib.__generator(this, function (_a) {
  2807. switch (_a.label) {
  2808. case 0: return [4 /*yield*/, this.assertedPersistence.setPersistence(_getInstance(persistence))];
  2809. case 1:
  2810. _a.sent();
  2811. return [2 /*return*/];
  2812. }
  2813. });
  2814. }); });
  2815. };
  2816. AuthImpl.prototype._getPersistence = function () {
  2817. return this.assertedPersistence.persistence.type;
  2818. };
  2819. AuthImpl.prototype._updateErrorMap = function (errorMap) {
  2820. this._errorFactory = new util.ErrorFactory('auth', 'Firebase', errorMap());
  2821. };
  2822. AuthImpl.prototype.onAuthStateChanged = function (nextOrObserver, error, completed) {
  2823. return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
  2824. };
  2825. AuthImpl.prototype.beforeAuthStateChanged = function (callback, onAbort) {
  2826. return this.beforeStateQueue.pushCallback(callback, onAbort);
  2827. };
  2828. AuthImpl.prototype.onIdTokenChanged = function (nextOrObserver, error, completed) {
  2829. return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
  2830. };
  2831. AuthImpl.prototype.toJSON = function () {
  2832. var _a;
  2833. return {
  2834. apiKey: this.config.apiKey,
  2835. authDomain: this.config.authDomain,
  2836. appName: this.name,
  2837. currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
  2838. };
  2839. };
  2840. AuthImpl.prototype._setRedirectUser = function (user, popupRedirectResolver) {
  2841. return tslib.__awaiter(this, void 0, void 0, function () {
  2842. var redirectManager;
  2843. return tslib.__generator(this, function (_a) {
  2844. switch (_a.label) {
  2845. case 0: return [4 /*yield*/, this.getOrInitRedirectPersistenceManager(popupRedirectResolver)];
  2846. case 1:
  2847. redirectManager = _a.sent();
  2848. return [2 /*return*/, user === null
  2849. ? redirectManager.removeCurrentUser()
  2850. : redirectManager.setCurrentUser(user)];
  2851. }
  2852. });
  2853. });
  2854. };
  2855. AuthImpl.prototype.getOrInitRedirectPersistenceManager = function (popupRedirectResolver) {
  2856. return tslib.__awaiter(this, void 0, void 0, function () {
  2857. var resolver, _a, _b;
  2858. return tslib.__generator(this, function (_c) {
  2859. switch (_c.label) {
  2860. case 0:
  2861. if (!!this.redirectPersistenceManager) return [3 /*break*/, 3];
  2862. resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
  2863. this._popupRedirectResolver;
  2864. _assert(resolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2865. _a = this;
  2866. return [4 /*yield*/, PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */)];
  2867. case 1:
  2868. _a.redirectPersistenceManager = _c.sent();
  2869. _b = this;
  2870. return [4 /*yield*/, this.redirectPersistenceManager.getCurrentUser()];
  2871. case 2:
  2872. _b.redirectUser =
  2873. _c.sent();
  2874. _c.label = 3;
  2875. case 3: return [2 /*return*/, this.redirectPersistenceManager];
  2876. }
  2877. });
  2878. });
  2879. };
  2880. AuthImpl.prototype._redirectUserForId = function (id) {
  2881. var _a, _b;
  2882. return tslib.__awaiter(this, void 0, void 0, function () {
  2883. var _this = this;
  2884. return tslib.__generator(this, function (_c) {
  2885. switch (_c.label) {
  2886. case 0:
  2887. if (!this._isInitialized) return [3 /*break*/, 2];
  2888. return [4 /*yield*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  2889. return [2 /*return*/];
  2890. }); }); })];
  2891. case 1:
  2892. _c.sent();
  2893. _c.label = 2;
  2894. case 2:
  2895. if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
  2896. return [2 /*return*/, this._currentUser];
  2897. }
  2898. if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
  2899. return [2 /*return*/, this.redirectUser];
  2900. }
  2901. return [2 /*return*/, null];
  2902. }
  2903. });
  2904. });
  2905. };
  2906. AuthImpl.prototype._persistUserIfCurrent = function (user) {
  2907. return tslib.__awaiter(this, void 0, void 0, function () {
  2908. var _this = this;
  2909. return tslib.__generator(this, function (_a) {
  2910. if (user === this.currentUser) {
  2911. return [2 /*return*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  2912. return [2 /*return*/, this.directlySetCurrentUser(user)];
  2913. }); }); })];
  2914. }
  2915. return [2 /*return*/];
  2916. });
  2917. });
  2918. };
  2919. /** Notifies listeners only if the user is current */
  2920. AuthImpl.prototype._notifyListenersIfCurrent = function (user) {
  2921. if (user === this.currentUser) {
  2922. this.notifyAuthListeners();
  2923. }
  2924. };
  2925. AuthImpl.prototype._key = function () {
  2926. return "".concat(this.config.authDomain, ":").concat(this.config.apiKey, ":").concat(this.name);
  2927. };
  2928. AuthImpl.prototype._startProactiveRefresh = function () {
  2929. this.isProactiveRefreshEnabled = true;
  2930. if (this.currentUser) {
  2931. this._currentUser._startProactiveRefresh();
  2932. }
  2933. };
  2934. AuthImpl.prototype._stopProactiveRefresh = function () {
  2935. this.isProactiveRefreshEnabled = false;
  2936. if (this.currentUser) {
  2937. this._currentUser._stopProactiveRefresh();
  2938. }
  2939. };
  2940. Object.defineProperty(AuthImpl.prototype, "_currentUser", {
  2941. /** Returns the current user cast as the internal type */
  2942. get: function () {
  2943. return this.currentUser;
  2944. },
  2945. enumerable: false,
  2946. configurable: true
  2947. });
  2948. AuthImpl.prototype.notifyAuthListeners = function () {
  2949. var _a, _b;
  2950. if (!this._isInitialized) {
  2951. return;
  2952. }
  2953. this.idTokenSubscription.next(this.currentUser);
  2954. var currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
  2955. if (this.lastNotifiedUid !== currentUid) {
  2956. this.lastNotifiedUid = currentUid;
  2957. this.authStateSubscription.next(this.currentUser);
  2958. }
  2959. };
  2960. AuthImpl.prototype.registerStateListener = function (subscription, nextOrObserver, error, completed) {
  2961. var _this = this;
  2962. if (this._deleted) {
  2963. return function () { };
  2964. }
  2965. var cb = typeof nextOrObserver === 'function'
  2966. ? nextOrObserver
  2967. : nextOrObserver.next.bind(nextOrObserver);
  2968. var promise = this._isInitialized
  2969. ? Promise.resolve()
  2970. : this._initializationPromise;
  2971. _assert(promise, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2972. // The callback needs to be called asynchronously per the spec.
  2973. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2974. promise.then(function () { return cb(_this.currentUser); });
  2975. if (typeof nextOrObserver === 'function') {
  2976. return subscription.addObserver(nextOrObserver, error, completed);
  2977. }
  2978. else {
  2979. return subscription.addObserver(nextOrObserver);
  2980. }
  2981. };
  2982. /**
  2983. * Unprotected (from race conditions) method to set the current user. This
  2984. * should only be called from within a queued callback. This is necessary
  2985. * because the queue shouldn't rely on another queued callback.
  2986. */
  2987. AuthImpl.prototype.directlySetCurrentUser = function (user) {
  2988. return tslib.__awaiter(this, void 0, void 0, function () {
  2989. return tslib.__generator(this, function (_a) {
  2990. switch (_a.label) {
  2991. case 0:
  2992. if (this.currentUser && this.currentUser !== user) {
  2993. this._currentUser._stopProactiveRefresh();
  2994. }
  2995. if (user && this.isProactiveRefreshEnabled) {
  2996. user._startProactiveRefresh();
  2997. }
  2998. this.currentUser = user;
  2999. if (!user) return [3 /*break*/, 2];
  3000. return [4 /*yield*/, this.assertedPersistence.setCurrentUser(user)];
  3001. case 1:
  3002. _a.sent();
  3003. return [3 /*break*/, 4];
  3004. case 2: return [4 /*yield*/, this.assertedPersistence.removeCurrentUser()];
  3005. case 3:
  3006. _a.sent();
  3007. _a.label = 4;
  3008. case 4: return [2 /*return*/];
  3009. }
  3010. });
  3011. });
  3012. };
  3013. AuthImpl.prototype.queue = function (action) {
  3014. // In case something errors, the callback still should be called in order
  3015. // to keep the promise chain alive
  3016. this.operations = this.operations.then(action, action);
  3017. return this.operations;
  3018. };
  3019. Object.defineProperty(AuthImpl.prototype, "assertedPersistence", {
  3020. get: function () {
  3021. _assert(this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3022. return this.persistenceManager;
  3023. },
  3024. enumerable: false,
  3025. configurable: true
  3026. });
  3027. AuthImpl.prototype._logFramework = function (framework) {
  3028. if (!framework || this.frameworks.includes(framework)) {
  3029. return;
  3030. }
  3031. this.frameworks.push(framework);
  3032. // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
  3033. // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
  3034. this.frameworks.sort();
  3035. this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  3036. };
  3037. AuthImpl.prototype._getFrameworks = function () {
  3038. return this.frameworks;
  3039. };
  3040. AuthImpl.prototype._getAdditionalHeaders = function () {
  3041. var _a;
  3042. return tslib.__awaiter(this, void 0, void 0, function () {
  3043. var headers, heartbeatsHeader;
  3044. var _b;
  3045. return tslib.__generator(this, function (_c) {
  3046. switch (_c.label) {
  3047. case 0:
  3048. headers = (_b = {},
  3049. _b["X-Client-Version" /* HttpHeader.X_CLIENT_VERSION */] = this.clientVersion,
  3050. _b);
  3051. if (this.app.options.appId) {
  3052. headers["X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;
  3053. }
  3054. return [4 /*yield*/, ((_a = this.heartbeatServiceProvider
  3055. .getImmediate({
  3056. optional: true
  3057. })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader())];
  3058. case 1:
  3059. heartbeatsHeader = _c.sent();
  3060. if (heartbeatsHeader) {
  3061. headers["X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;
  3062. }
  3063. return [2 /*return*/, headers];
  3064. }
  3065. });
  3066. });
  3067. };
  3068. return AuthImpl;
  3069. }());
  3070. /**
  3071. * Method to be used to cast down to our private implmentation of Auth.
  3072. * It will also handle unwrapping from the compat type if necessary
  3073. *
  3074. * @param auth Auth object passed in from developer
  3075. */
  3076. function _castAuth(auth) {
  3077. return util.getModularInstance(auth);
  3078. }
  3079. /** Helper class to wrap subscriber logic */
  3080. var Subscription = /** @class */ (function () {
  3081. function Subscription(auth) {
  3082. var _this = this;
  3083. this.auth = auth;
  3084. this.observer = null;
  3085. this.addObserver = util.createSubscribe(function (observer) { return (_this.observer = observer); });
  3086. }
  3087. Object.defineProperty(Subscription.prototype, "next", {
  3088. get: function () {
  3089. _assert(this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3090. return this.observer.next.bind(this.observer);
  3091. },
  3092. enumerable: false,
  3093. configurable: true
  3094. });
  3095. return Subscription;
  3096. }());
  3097. /**
  3098. * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
  3099. * Firebase Auth services.
  3100. *
  3101. * @remarks
  3102. * This must be called synchronously immediately following the first call to
  3103. * {@link initializeAuth}. Do not use with production credentials as emulator
  3104. * traffic is not encrypted.
  3105. *
  3106. *
  3107. * @example
  3108. * ```javascript
  3109. * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
  3110. * ```
  3111. *
  3112. * @param auth - The {@link Auth} instance.
  3113. * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
  3114. * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
  3115. * `true` to disable the warning banner attached to the DOM.
  3116. *
  3117. * @public
  3118. */
  3119. function connectAuthEmulator(auth, url, options) {
  3120. var authInternal = _castAuth(auth);
  3121. _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);
  3122. _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);
  3123. var disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
  3124. var protocol = extractProtocol(url);
  3125. var _a = extractHostAndPort(url), host = _a.host, port = _a.port;
  3126. var portStr = port === null ? '' : ":".concat(port);
  3127. // Always replace path with "/" (even if input url had no path at all, or had a different one).
  3128. authInternal.config.emulator = { url: "".concat(protocol, "//").concat(host).concat(portStr, "/") };
  3129. authInternal.settings.appVerificationDisabledForTesting = true;
  3130. authInternal.emulatorConfig = Object.freeze({
  3131. host: host,
  3132. port: port,
  3133. protocol: protocol.replace(':', ''),
  3134. options: Object.freeze({ disableWarnings: disableWarnings })
  3135. });
  3136. if (!disableWarnings) {
  3137. emitEmulatorWarning();
  3138. }
  3139. }
  3140. function extractProtocol(url) {
  3141. var protocolEnd = url.indexOf(':');
  3142. return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
  3143. }
  3144. function extractHostAndPort(url) {
  3145. var protocol = extractProtocol(url);
  3146. var authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
  3147. if (!authority) {
  3148. return { host: '', port: null };
  3149. }
  3150. var hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
  3151. var bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  3152. if (bracketedIPv6) {
  3153. var host = bracketedIPv6[1];
  3154. return { host: host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  3155. }
  3156. else {
  3157. var _a = hostAndPort.split(':'), host = _a[0], port = _a[1];
  3158. return { host: host, port: parsePort(port) };
  3159. }
  3160. }
  3161. function parsePort(portStr) {
  3162. if (!portStr) {
  3163. return null;
  3164. }
  3165. var port = Number(portStr);
  3166. if (isNaN(port)) {
  3167. return null;
  3168. }
  3169. return port;
  3170. }
  3171. function emitEmulatorWarning() {
  3172. function attachBanner() {
  3173. var el = document.createElement('p');
  3174. var sty = el.style;
  3175. el.innerText =
  3176. 'Running in emulator mode. Do not use with production credentials.';
  3177. sty.position = 'fixed';
  3178. sty.width = '100%';
  3179. sty.backgroundColor = '#ffffff';
  3180. sty.border = '.1em solid #000000';
  3181. sty.color = '#b50000';
  3182. sty.bottom = '0px';
  3183. sty.left = '0px';
  3184. sty.margin = '0px';
  3185. sty.zIndex = '10000';
  3186. sty.textAlign = 'center';
  3187. el.classList.add('firebase-emulator-warning');
  3188. document.body.appendChild(el);
  3189. }
  3190. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  3191. console.info('WARNING: You are using the Auth Emulator,' +
  3192. ' which is intended for local testing only. Do not use with' +
  3193. ' production credentials.');
  3194. }
  3195. if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  3196. if (document.readyState === 'loading') {
  3197. window.addEventListener('DOMContentLoaded', attachBanner);
  3198. }
  3199. else {
  3200. attachBanner();
  3201. }
  3202. }
  3203. }
  3204. /**
  3205. * @license
  3206. * Copyright 2020 Google LLC
  3207. *
  3208. * Licensed under the Apache License, Version 2.0 (the "License");
  3209. * you may not use this file except in compliance with the License.
  3210. * You may obtain a copy of the License at
  3211. *
  3212. * http://www.apache.org/licenses/LICENSE-2.0
  3213. *
  3214. * Unless required by applicable law or agreed to in writing, software
  3215. * distributed under the License is distributed on an "AS IS" BASIS,
  3216. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3217. * See the License for the specific language governing permissions and
  3218. * limitations under the License.
  3219. */
  3220. /**
  3221. * Interface that represents the credentials returned by an {@link AuthProvider}.
  3222. *
  3223. * @remarks
  3224. * Implementations specify the details about each auth provider's credential requirements.
  3225. *
  3226. * @public
  3227. */
  3228. var AuthCredential = /** @class */ (function () {
  3229. /** @internal */
  3230. function AuthCredential(
  3231. /**
  3232. * The authentication provider ID for the credential.
  3233. *
  3234. * @remarks
  3235. * For example, 'facebook.com', or 'google.com'.
  3236. */
  3237. providerId,
  3238. /**
  3239. * The authentication sign in method for the credential.
  3240. *
  3241. * @remarks
  3242. * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
  3243. * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
  3244. * identifier as returned in {@link fetchSignInMethodsForEmail}.
  3245. */
  3246. signInMethod) {
  3247. this.providerId = providerId;
  3248. this.signInMethod = signInMethod;
  3249. }
  3250. /**
  3251. * Returns a JSON-serializable representation of this object.
  3252. *
  3253. * @returns a JSON-serializable representation of this object.
  3254. */
  3255. AuthCredential.prototype.toJSON = function () {
  3256. return debugFail('not implemented');
  3257. };
  3258. /** @internal */
  3259. AuthCredential.prototype._getIdTokenResponse = function (_auth) {
  3260. return debugFail('not implemented');
  3261. };
  3262. /** @internal */
  3263. AuthCredential.prototype._linkToIdToken = function (_auth, _idToken) {
  3264. return debugFail('not implemented');
  3265. };
  3266. /** @internal */
  3267. AuthCredential.prototype._getReauthenticationResolver = function (_auth) {
  3268. return debugFail('not implemented');
  3269. };
  3270. return AuthCredential;
  3271. }());
  3272. /**
  3273. * @license
  3274. * Copyright 2020 Google LLC
  3275. *
  3276. * Licensed under the Apache License, Version 2.0 (the "License");
  3277. * you may not use this file except in compliance with the License.
  3278. * You may obtain a copy of the License at
  3279. *
  3280. * http://www.apache.org/licenses/LICENSE-2.0
  3281. *
  3282. * Unless required by applicable law or agreed to in writing, software
  3283. * distributed under the License is distributed on an "AS IS" BASIS,
  3284. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3285. * See the License for the specific language governing permissions and
  3286. * limitations under the License.
  3287. */
  3288. function resetPassword(auth, request) {
  3289. return tslib.__awaiter(this, void 0, void 0, function () {
  3290. return tslib.__generator(this, function (_a) {
  3291. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:resetPassword" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request))];
  3292. });
  3293. });
  3294. }
  3295. function updateEmailPassword(auth, request) {
  3296. return tslib.__awaiter(this, void 0, void 0, function () {
  3297. return tslib.__generator(this, function (_a) {
  3298. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  3299. });
  3300. });
  3301. }
  3302. function applyActionCode$1(auth, request) {
  3303. return tslib.__awaiter(this, void 0, void 0, function () {
  3304. return tslib.__generator(this, function (_a) {
  3305. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request))];
  3306. });
  3307. });
  3308. }
  3309. /**
  3310. * @license
  3311. * Copyright 2020 Google LLC
  3312. *
  3313. * Licensed under the Apache License, Version 2.0 (the "License");
  3314. * you may not use this file except in compliance with the License.
  3315. * You may obtain a copy of the License at
  3316. *
  3317. * http://www.apache.org/licenses/LICENSE-2.0
  3318. *
  3319. * Unless required by applicable law or agreed to in writing, software
  3320. * distributed under the License is distributed on an "AS IS" BASIS,
  3321. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3322. * See the License for the specific language governing permissions and
  3323. * limitations under the License.
  3324. */
  3325. function signInWithPassword(auth, request) {
  3326. return tslib.__awaiter(this, void 0, void 0, function () {
  3327. return tslib.__generator(this, function (_a) {
  3328. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPassword" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request))];
  3329. });
  3330. });
  3331. }
  3332. function sendOobCode(auth, request) {
  3333. return tslib.__awaiter(this, void 0, void 0, function () {
  3334. return tslib.__generator(this, function (_a) {
  3335. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendOobCode" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request))];
  3336. });
  3337. });
  3338. }
  3339. function sendEmailVerification$1(auth, request) {
  3340. return tslib.__awaiter(this, void 0, void 0, function () {
  3341. return tslib.__generator(this, function (_a) {
  3342. return [2 /*return*/, sendOobCode(auth, request)];
  3343. });
  3344. });
  3345. }
  3346. function sendPasswordResetEmail$1(auth, request) {
  3347. return tslib.__awaiter(this, void 0, void 0, function () {
  3348. return tslib.__generator(this, function (_a) {
  3349. return [2 /*return*/, sendOobCode(auth, request)];
  3350. });
  3351. });
  3352. }
  3353. function sendSignInLinkToEmail$1(auth, request) {
  3354. return tslib.__awaiter(this, void 0, void 0, function () {
  3355. return tslib.__generator(this, function (_a) {
  3356. return [2 /*return*/, sendOobCode(auth, request)];
  3357. });
  3358. });
  3359. }
  3360. function verifyAndChangeEmail(auth, request) {
  3361. return tslib.__awaiter(this, void 0, void 0, function () {
  3362. return tslib.__generator(this, function (_a) {
  3363. return [2 /*return*/, sendOobCode(auth, request)];
  3364. });
  3365. });
  3366. }
  3367. /**
  3368. * @license
  3369. * Copyright 2020 Google LLC
  3370. *
  3371. * Licensed under the Apache License, Version 2.0 (the "License");
  3372. * you may not use this file except in compliance with the License.
  3373. * You may obtain a copy of the License at
  3374. *
  3375. * http://www.apache.org/licenses/LICENSE-2.0
  3376. *
  3377. * Unless required by applicable law or agreed to in writing, software
  3378. * distributed under the License is distributed on an "AS IS" BASIS,
  3379. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3380. * See the License for the specific language governing permissions and
  3381. * limitations under the License.
  3382. */
  3383. function signInWithEmailLink$1(auth, request) {
  3384. return tslib.__awaiter(this, void 0, void 0, function () {
  3385. return tslib.__generator(this, function (_a) {
  3386. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  3387. });
  3388. });
  3389. }
  3390. function signInWithEmailLinkForLinking(auth, request) {
  3391. return tslib.__awaiter(this, void 0, void 0, function () {
  3392. return tslib.__generator(this, function (_a) {
  3393. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  3394. });
  3395. });
  3396. }
  3397. /**
  3398. * @license
  3399. * Copyright 2020 Google LLC
  3400. *
  3401. * Licensed under the Apache License, Version 2.0 (the "License");
  3402. * you may not use this file except in compliance with the License.
  3403. * You may obtain a copy of the License at
  3404. *
  3405. * http://www.apache.org/licenses/LICENSE-2.0
  3406. *
  3407. * Unless required by applicable law or agreed to in writing, software
  3408. * distributed under the License is distributed on an "AS IS" BASIS,
  3409. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3410. * See the License for the specific language governing permissions and
  3411. * limitations under the License.
  3412. */
  3413. /**
  3414. * Interface that represents the credentials returned by {@link EmailAuthProvider} for
  3415. * {@link ProviderId}.PASSWORD
  3416. *
  3417. * @remarks
  3418. * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
  3419. * {@link SignInMethod}.EMAIL_LINK.
  3420. *
  3421. * @public
  3422. */
  3423. var EmailAuthCredential = /** @class */ (function (_super) {
  3424. tslib.__extends(EmailAuthCredential, _super);
  3425. /** @internal */
  3426. function EmailAuthCredential(
  3427. /** @internal */
  3428. _email,
  3429. /** @internal */
  3430. _password, signInMethod,
  3431. /** @internal */
  3432. _tenantId) {
  3433. if (_tenantId === void 0) { _tenantId = null; }
  3434. var _this = _super.call(this, "password" /* ProviderId.PASSWORD */, signInMethod) || this;
  3435. _this._email = _email;
  3436. _this._password = _password;
  3437. _this._tenantId = _tenantId;
  3438. return _this;
  3439. }
  3440. /** @internal */
  3441. EmailAuthCredential._fromEmailAndPassword = function (email, password) {
  3442. return new EmailAuthCredential(email, password, "password" /* SignInMethod.EMAIL_PASSWORD */);
  3443. };
  3444. /** @internal */
  3445. EmailAuthCredential._fromEmailAndCode = function (email, oobCode, tenantId) {
  3446. if (tenantId === void 0) { tenantId = null; }
  3447. return new EmailAuthCredential(email, oobCode, "emailLink" /* SignInMethod.EMAIL_LINK */, tenantId);
  3448. };
  3449. /** {@inheritdoc AuthCredential.toJSON} */
  3450. EmailAuthCredential.prototype.toJSON = function () {
  3451. return {
  3452. email: this._email,
  3453. password: this._password,
  3454. signInMethod: this.signInMethod,
  3455. tenantId: this._tenantId
  3456. };
  3457. };
  3458. /**
  3459. * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
  3460. *
  3461. * @param json - Either `object` or the stringified representation of the object. When string is
  3462. * provided, `JSON.parse` would be called first.
  3463. *
  3464. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3465. */
  3466. EmailAuthCredential.fromJSON = function (json) {
  3467. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  3468. if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
  3469. if (obj.signInMethod === "password" /* SignInMethod.EMAIL_PASSWORD */) {
  3470. return this._fromEmailAndPassword(obj.email, obj.password);
  3471. }
  3472. else if (obj.signInMethod === "emailLink" /* SignInMethod.EMAIL_LINK */) {
  3473. return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
  3474. }
  3475. }
  3476. return null;
  3477. };
  3478. /** @internal */
  3479. EmailAuthCredential.prototype._getIdTokenResponse = function (auth) {
  3480. return tslib.__awaiter(this, void 0, void 0, function () {
  3481. return tslib.__generator(this, function (_a) {
  3482. switch (this.signInMethod) {
  3483. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  3484. return [2 /*return*/, signInWithPassword(auth, {
  3485. returnSecureToken: true,
  3486. email: this._email,
  3487. password: this._password
  3488. })];
  3489. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  3490. return [2 /*return*/, signInWithEmailLink$1(auth, {
  3491. email: this._email,
  3492. oobCode: this._password
  3493. })];
  3494. default:
  3495. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3496. }
  3497. return [2 /*return*/];
  3498. });
  3499. });
  3500. };
  3501. /** @internal */
  3502. EmailAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  3503. return tslib.__awaiter(this, void 0, void 0, function () {
  3504. return tslib.__generator(this, function (_a) {
  3505. switch (this.signInMethod) {
  3506. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  3507. return [2 /*return*/, updateEmailPassword(auth, {
  3508. idToken: idToken,
  3509. returnSecureToken: true,
  3510. email: this._email,
  3511. password: this._password
  3512. })];
  3513. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  3514. return [2 /*return*/, signInWithEmailLinkForLinking(auth, {
  3515. idToken: idToken,
  3516. email: this._email,
  3517. oobCode: this._password
  3518. })];
  3519. default:
  3520. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3521. }
  3522. return [2 /*return*/];
  3523. });
  3524. });
  3525. };
  3526. /** @internal */
  3527. EmailAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  3528. return this._getIdTokenResponse(auth);
  3529. };
  3530. return EmailAuthCredential;
  3531. }(AuthCredential));
  3532. /**
  3533. * @license
  3534. * Copyright 2020 Google LLC
  3535. *
  3536. * Licensed under the Apache License, Version 2.0 (the "License");
  3537. * you may not use this file except in compliance with the License.
  3538. * You may obtain a copy of the License at
  3539. *
  3540. * http://www.apache.org/licenses/LICENSE-2.0
  3541. *
  3542. * Unless required by applicable law or agreed to in writing, software
  3543. * distributed under the License is distributed on an "AS IS" BASIS,
  3544. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3545. * See the License for the specific language governing permissions and
  3546. * limitations under the License.
  3547. */
  3548. function signInWithIdp(auth, request) {
  3549. return tslib.__awaiter(this, void 0, void 0, function () {
  3550. return tslib.__generator(this, function (_a) {
  3551. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithIdp" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request))];
  3552. });
  3553. });
  3554. }
  3555. /**
  3556. * @license
  3557. * Copyright 2020 Google LLC
  3558. *
  3559. * Licensed under the Apache License, Version 2.0 (the "License");
  3560. * you may not use this file except in compliance with the License.
  3561. * You may obtain a copy of the License at
  3562. *
  3563. * http://www.apache.org/licenses/LICENSE-2.0
  3564. *
  3565. * Unless required by applicable law or agreed to in writing, software
  3566. * distributed under the License is distributed on an "AS IS" BASIS,
  3567. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3568. * See the License for the specific language governing permissions and
  3569. * limitations under the License.
  3570. */
  3571. var IDP_REQUEST_URI$1 = 'http://localhost';
  3572. /**
  3573. * Represents the OAuth credentials returned by an {@link OAuthProvider}.
  3574. *
  3575. * @remarks
  3576. * Implementations specify the details about each auth provider's credential requirements.
  3577. *
  3578. * @public
  3579. */
  3580. var OAuthCredential = /** @class */ (function (_super) {
  3581. tslib.__extends(OAuthCredential, _super);
  3582. function OAuthCredential() {
  3583. var _this = _super !== null && _super.apply(this, arguments) || this;
  3584. _this.pendingToken = null;
  3585. return _this;
  3586. }
  3587. /** @internal */
  3588. OAuthCredential._fromParams = function (params) {
  3589. var cred = new OAuthCredential(params.providerId, params.signInMethod);
  3590. if (params.idToken || params.accessToken) {
  3591. // OAuth 2 and either ID token or access token.
  3592. if (params.idToken) {
  3593. cred.idToken = params.idToken;
  3594. }
  3595. if (params.accessToken) {
  3596. cred.accessToken = params.accessToken;
  3597. }
  3598. // Add nonce if available and no pendingToken is present.
  3599. if (params.nonce && !params.pendingToken) {
  3600. cred.nonce = params.nonce;
  3601. }
  3602. if (params.pendingToken) {
  3603. cred.pendingToken = params.pendingToken;
  3604. }
  3605. }
  3606. else if (params.oauthToken && params.oauthTokenSecret) {
  3607. // OAuth 1 and OAuth token with token secret
  3608. cred.accessToken = params.oauthToken;
  3609. cred.secret = params.oauthTokenSecret;
  3610. }
  3611. else {
  3612. _fail("argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3613. }
  3614. return cred;
  3615. };
  3616. /** {@inheritdoc AuthCredential.toJSON} */
  3617. OAuthCredential.prototype.toJSON = function () {
  3618. return {
  3619. idToken: this.idToken,
  3620. accessToken: this.accessToken,
  3621. secret: this.secret,
  3622. nonce: this.nonce,
  3623. pendingToken: this.pendingToken,
  3624. providerId: this.providerId,
  3625. signInMethod: this.signInMethod
  3626. };
  3627. };
  3628. /**
  3629. * Static method to deserialize a JSON representation of an object into an
  3630. * {@link AuthCredential}.
  3631. *
  3632. * @param json - Input can be either Object or the stringified representation of the object.
  3633. * When string is provided, JSON.parse would be called first.
  3634. *
  3635. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3636. */
  3637. OAuthCredential.fromJSON = function (json) {
  3638. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  3639. var providerId = obj.providerId, signInMethod = obj.signInMethod, rest = tslib.__rest(obj, ["providerId", "signInMethod"]);
  3640. if (!providerId || !signInMethod) {
  3641. return null;
  3642. }
  3643. var cred = new OAuthCredential(providerId, signInMethod);
  3644. cred.idToken = rest.idToken || undefined;
  3645. cred.accessToken = rest.accessToken || undefined;
  3646. cred.secret = rest.secret;
  3647. cred.nonce = rest.nonce;
  3648. cred.pendingToken = rest.pendingToken || null;
  3649. return cred;
  3650. };
  3651. /** @internal */
  3652. OAuthCredential.prototype._getIdTokenResponse = function (auth) {
  3653. var request = this.buildRequest();
  3654. return signInWithIdp(auth, request);
  3655. };
  3656. /** @internal */
  3657. OAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  3658. var request = this.buildRequest();
  3659. request.idToken = idToken;
  3660. return signInWithIdp(auth, request);
  3661. };
  3662. /** @internal */
  3663. OAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  3664. var request = this.buildRequest();
  3665. request.autoCreate = false;
  3666. return signInWithIdp(auth, request);
  3667. };
  3668. OAuthCredential.prototype.buildRequest = function () {
  3669. var request = {
  3670. requestUri: IDP_REQUEST_URI$1,
  3671. returnSecureToken: true
  3672. };
  3673. if (this.pendingToken) {
  3674. request.pendingToken = this.pendingToken;
  3675. }
  3676. else {
  3677. var postBody = {};
  3678. if (this.idToken) {
  3679. postBody['id_token'] = this.idToken;
  3680. }
  3681. if (this.accessToken) {
  3682. postBody['access_token'] = this.accessToken;
  3683. }
  3684. if (this.secret) {
  3685. postBody['oauth_token_secret'] = this.secret;
  3686. }
  3687. postBody['providerId'] = this.providerId;
  3688. if (this.nonce && !this.pendingToken) {
  3689. postBody['nonce'] = this.nonce;
  3690. }
  3691. request.postBody = util.querystring(postBody);
  3692. }
  3693. return request;
  3694. };
  3695. return OAuthCredential;
  3696. }(AuthCredential));
  3697. /**
  3698. * @license
  3699. * Copyright 2020 Google LLC
  3700. *
  3701. * Licensed under the Apache License, Version 2.0 (the "License");
  3702. * you may not use this file except in compliance with the License.
  3703. * You may obtain a copy of the License at
  3704. *
  3705. * http://www.apache.org/licenses/LICENSE-2.0
  3706. *
  3707. * Unless required by applicable law or agreed to in writing, software
  3708. * distributed under the License is distributed on an "AS IS" BASIS,
  3709. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3710. * See the License for the specific language governing permissions and
  3711. * limitations under the License.
  3712. */
  3713. var _a;
  3714. function sendPhoneVerificationCode(auth, request) {
  3715. return tslib.__awaiter(this, void 0, void 0, function () {
  3716. return tslib.__generator(this, function (_a) {
  3717. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendVerificationCode" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request))];
  3718. });
  3719. });
  3720. }
  3721. function signInWithPhoneNumber$1(auth, request) {
  3722. return tslib.__awaiter(this, void 0, void 0, function () {
  3723. return tslib.__generator(this, function (_a) {
  3724. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  3725. });
  3726. });
  3727. }
  3728. function linkWithPhoneNumber$1(auth, request) {
  3729. return tslib.__awaiter(this, void 0, void 0, function () {
  3730. var response;
  3731. return tslib.__generator(this, function (_a) {
  3732. switch (_a.label) {
  3733. case 0: return [4 /*yield*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  3734. case 1:
  3735. response = _a.sent();
  3736. if (response.temporaryProof) {
  3737. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, response);
  3738. }
  3739. return [2 /*return*/, response];
  3740. }
  3741. });
  3742. });
  3743. }
  3744. var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = (_a = {},
  3745. _a["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  3746. _a);
  3747. function verifyPhoneNumberForExisting(auth, request) {
  3748. return tslib.__awaiter(this, void 0, void 0, function () {
  3749. var apiRequest;
  3750. return tslib.__generator(this, function (_a) {
  3751. apiRequest = tslib.__assign(tslib.__assign({}, request), { operation: 'REAUTH' });
  3752. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_)];
  3753. });
  3754. });
  3755. }
  3756. /**
  3757. * @license
  3758. * Copyright 2020 Google LLC
  3759. *
  3760. * Licensed under the Apache License, Version 2.0 (the "License");
  3761. * you may not use this file except in compliance with the License.
  3762. * You may obtain a copy of the License at
  3763. *
  3764. * http://www.apache.org/licenses/LICENSE-2.0
  3765. *
  3766. * Unless required by applicable law or agreed to in writing, software
  3767. * distributed under the License is distributed on an "AS IS" BASIS,
  3768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3769. * See the License for the specific language governing permissions and
  3770. * limitations under the License.
  3771. */
  3772. /**
  3773. * Represents the credentials returned by {@link PhoneAuthProvider}.
  3774. *
  3775. * @public
  3776. */
  3777. var PhoneAuthCredential = /** @class */ (function (_super) {
  3778. tslib.__extends(PhoneAuthCredential, _super);
  3779. function PhoneAuthCredential(params) {
  3780. var _this = _super.call(this, "phone" /* ProviderId.PHONE */, "phone" /* SignInMethod.PHONE */) || this;
  3781. _this.params = params;
  3782. return _this;
  3783. }
  3784. /** @internal */
  3785. PhoneAuthCredential._fromVerification = function (verificationId, verificationCode) {
  3786. return new PhoneAuthCredential({ verificationId: verificationId, verificationCode: verificationCode });
  3787. };
  3788. /** @internal */
  3789. PhoneAuthCredential._fromTokenResponse = function (phoneNumber, temporaryProof) {
  3790. return new PhoneAuthCredential({ phoneNumber: phoneNumber, temporaryProof: temporaryProof });
  3791. };
  3792. /** @internal */
  3793. PhoneAuthCredential.prototype._getIdTokenResponse = function (auth) {
  3794. return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
  3795. };
  3796. /** @internal */
  3797. PhoneAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  3798. return linkWithPhoneNumber$1(auth, tslib.__assign({ idToken: idToken }, this._makeVerificationRequest()));
  3799. };
  3800. /** @internal */
  3801. PhoneAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  3802. return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
  3803. };
  3804. /** @internal */
  3805. PhoneAuthCredential.prototype._makeVerificationRequest = function () {
  3806. var _a = this.params, temporaryProof = _a.temporaryProof, phoneNumber = _a.phoneNumber, verificationId = _a.verificationId, verificationCode = _a.verificationCode;
  3807. if (temporaryProof && phoneNumber) {
  3808. return { temporaryProof: temporaryProof, phoneNumber: phoneNumber };
  3809. }
  3810. return {
  3811. sessionInfo: verificationId,
  3812. code: verificationCode
  3813. };
  3814. };
  3815. /** {@inheritdoc AuthCredential.toJSON} */
  3816. PhoneAuthCredential.prototype.toJSON = function () {
  3817. var obj = {
  3818. providerId: this.providerId
  3819. };
  3820. if (this.params.phoneNumber) {
  3821. obj.phoneNumber = this.params.phoneNumber;
  3822. }
  3823. if (this.params.temporaryProof) {
  3824. obj.temporaryProof = this.params.temporaryProof;
  3825. }
  3826. if (this.params.verificationCode) {
  3827. obj.verificationCode = this.params.verificationCode;
  3828. }
  3829. if (this.params.verificationId) {
  3830. obj.verificationId = this.params.verificationId;
  3831. }
  3832. return obj;
  3833. };
  3834. /** Generates a phone credential based on a plain object or a JSON string. */
  3835. PhoneAuthCredential.fromJSON = function (json) {
  3836. if (typeof json === 'string') {
  3837. json = JSON.parse(json);
  3838. }
  3839. var _a = json, verificationId = _a.verificationId, verificationCode = _a.verificationCode, phoneNumber = _a.phoneNumber, temporaryProof = _a.temporaryProof;
  3840. if (!verificationCode &&
  3841. !verificationId &&
  3842. !phoneNumber &&
  3843. !temporaryProof) {
  3844. return null;
  3845. }
  3846. return new PhoneAuthCredential({
  3847. verificationId: verificationId,
  3848. verificationCode: verificationCode,
  3849. phoneNumber: phoneNumber,
  3850. temporaryProof: temporaryProof
  3851. });
  3852. };
  3853. return PhoneAuthCredential;
  3854. }(AuthCredential));
  3855. /**
  3856. * @license
  3857. * Copyright 2020 Google LLC
  3858. *
  3859. * Licensed under the Apache License, Version 2.0 (the "License");
  3860. * you may not use this file except in compliance with the License.
  3861. * You may obtain a copy of the License at
  3862. *
  3863. * http://www.apache.org/licenses/LICENSE-2.0
  3864. *
  3865. * Unless required by applicable law or agreed to in writing, software
  3866. * distributed under the License is distributed on an "AS IS" BASIS,
  3867. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3868. * See the License for the specific language governing permissions and
  3869. * limitations under the License.
  3870. */
  3871. /**
  3872. * Maps the mode string in action code URL to Action Code Info operation.
  3873. *
  3874. * @param mode
  3875. */
  3876. function parseMode(mode) {
  3877. switch (mode) {
  3878. case 'recoverEmail':
  3879. return "RECOVER_EMAIL" /* ActionCodeOperation.RECOVER_EMAIL */;
  3880. case 'resetPassword':
  3881. return "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */;
  3882. case 'signIn':
  3883. return "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  3884. case 'verifyEmail':
  3885. return "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */;
  3886. case 'verifyAndChangeEmail':
  3887. return "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;
  3888. case 'revertSecondFactorAddition':
  3889. return "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;
  3890. default:
  3891. return null;
  3892. }
  3893. }
  3894. /**
  3895. * Helper to parse FDL links
  3896. *
  3897. * @param url
  3898. */
  3899. function parseDeepLink(url) {
  3900. var link = util.querystringDecode(util.extractQuerystring(url))['link'];
  3901. // Double link case (automatic redirect).
  3902. var doubleDeepLink = link
  3903. ? util.querystringDecode(util.extractQuerystring(link))['deep_link_id']
  3904. : null;
  3905. // iOS custom scheme links.
  3906. var iOSDeepLink = util.querystringDecode(util.extractQuerystring(url))['deep_link_id'];
  3907. var iOSDoubleDeepLink = iOSDeepLink
  3908. ? util.querystringDecode(util.extractQuerystring(iOSDeepLink))['link']
  3909. : null;
  3910. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  3911. }
  3912. /**
  3913. * A utility class to parse email action URLs such as password reset, email verification,
  3914. * email link sign in, etc.
  3915. *
  3916. * @public
  3917. */
  3918. var ActionCodeURL = /** @class */ (function () {
  3919. /**
  3920. * @param actionLink - The link from which to extract the URL.
  3921. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  3922. *
  3923. * @internal
  3924. */
  3925. function ActionCodeURL(actionLink) {
  3926. var _a, _b, _c, _d, _e, _f;
  3927. var searchParams = util.querystringDecode(util.extractQuerystring(actionLink));
  3928. var apiKey = (_a = searchParams["apiKey" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;
  3929. var code = (_b = searchParams["oobCode" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;
  3930. var operation = parseMode((_c = searchParams["mode" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);
  3931. // Validate API key, code and mode.
  3932. _assert(apiKey && code && operation, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3933. this.apiKey = apiKey;
  3934. this.operation = operation;
  3935. this.code = code;
  3936. this.continueUrl = (_d = searchParams["continueUrl" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
  3937. this.languageCode = (_e = searchParams["languageCode" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
  3938. this.tenantId = (_f = searchParams["tenantId" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
  3939. }
  3940. /**
  3941. * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
  3942. * otherwise returns null.
  3943. *
  3944. * @param link - The email action link string.
  3945. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  3946. *
  3947. * @public
  3948. */
  3949. ActionCodeURL.parseLink = function (link) {
  3950. var actionLink = parseDeepLink(link);
  3951. try {
  3952. return new ActionCodeURL(actionLink);
  3953. }
  3954. catch (_a) {
  3955. return null;
  3956. }
  3957. };
  3958. return ActionCodeURL;
  3959. }());
  3960. /**
  3961. * Parses the email action link string and returns an {@link ActionCodeURL} if
  3962. * the link is valid, otherwise returns null.
  3963. *
  3964. * @public
  3965. */
  3966. function parseActionCodeURL(link) {
  3967. return ActionCodeURL.parseLink(link);
  3968. }
  3969. /**
  3970. * @license
  3971. * Copyright 2020 Google LLC
  3972. *
  3973. * Licensed under the Apache License, Version 2.0 (the "License");
  3974. * you may not use this file except in compliance with the License.
  3975. * You may obtain a copy of the License at
  3976. *
  3977. * http://www.apache.org/licenses/LICENSE-2.0
  3978. *
  3979. * Unless required by applicable law or agreed to in writing, software
  3980. * distributed under the License is distributed on an "AS IS" BASIS,
  3981. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3982. * See the License for the specific language governing permissions and
  3983. * limitations under the License.
  3984. */
  3985. /**
  3986. * Provider for generating {@link EmailAuthCredential}.
  3987. *
  3988. * @public
  3989. */
  3990. var EmailAuthProvider = /** @class */ (function () {
  3991. function EmailAuthProvider() {
  3992. /**
  3993. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  3994. */
  3995. this.providerId = EmailAuthProvider.PROVIDER_ID;
  3996. }
  3997. /**
  3998. * Initialize an {@link AuthCredential} using an email and password.
  3999. *
  4000. * @example
  4001. * ```javascript
  4002. * const authCredential = EmailAuthProvider.credential(email, password);
  4003. * const userCredential = await signInWithCredential(auth, authCredential);
  4004. * ```
  4005. *
  4006. * @example
  4007. * ```javascript
  4008. * const userCredential = await signInWithEmailAndPassword(auth, email, password);
  4009. * ```
  4010. *
  4011. * @param email - Email address.
  4012. * @param password - User account password.
  4013. * @returns The auth provider credential.
  4014. */
  4015. EmailAuthProvider.credential = function (email, password) {
  4016. return EmailAuthCredential._fromEmailAndPassword(email, password);
  4017. };
  4018. /**
  4019. * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
  4020. * email link operation.
  4021. *
  4022. * @example
  4023. * ```javascript
  4024. * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
  4025. * const userCredential = await signInWithCredential(auth, authCredential);
  4026. * ```
  4027. *
  4028. * @example
  4029. * ```javascript
  4030. * await sendSignInLinkToEmail(auth, email);
  4031. * // Obtain emailLink from user.
  4032. * const userCredential = await signInWithEmailLink(auth, email, emailLink);
  4033. * ```
  4034. *
  4035. * @param auth - The {@link Auth} instance used to verify the link.
  4036. * @param email - Email address.
  4037. * @param emailLink - Sign-in email link.
  4038. * @returns - The auth provider credential.
  4039. */
  4040. EmailAuthProvider.credentialWithLink = function (email, emailLink) {
  4041. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  4042. _assert(actionCodeUrl, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4043. return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  4044. };
  4045. /**
  4046. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  4047. */
  4048. EmailAuthProvider.PROVIDER_ID = "password" /* ProviderId.PASSWORD */;
  4049. /**
  4050. * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
  4051. */
  4052. EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* SignInMethod.EMAIL_PASSWORD */;
  4053. /**
  4054. * Always set to {@link SignInMethod}.EMAIL_LINK.
  4055. */
  4056. EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* SignInMethod.EMAIL_LINK */;
  4057. return EmailAuthProvider;
  4058. }());
  4059. /**
  4060. * @license
  4061. * Copyright 2020 Google LLC
  4062. *
  4063. * Licensed under the Apache License, Version 2.0 (the "License");
  4064. * you may not use this file except in compliance with the License.
  4065. * You may obtain a copy of the License at
  4066. *
  4067. * http://www.apache.org/licenses/LICENSE-2.0
  4068. *
  4069. * Unless required by applicable law or agreed to in writing, software
  4070. * distributed under the License is distributed on an "AS IS" BASIS,
  4071. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4072. * See the License for the specific language governing permissions and
  4073. * limitations under the License.
  4074. */
  4075. /**
  4076. * The base class for all Federated providers (OAuth (including OIDC), SAML).
  4077. *
  4078. * This class is not meant to be instantiated directly.
  4079. *
  4080. * @public
  4081. */
  4082. var FederatedAuthProvider = /** @class */ (function () {
  4083. /**
  4084. * Constructor for generic OAuth providers.
  4085. *
  4086. * @param providerId - Provider for which credentials should be generated.
  4087. */
  4088. function FederatedAuthProvider(providerId) {
  4089. this.providerId = providerId;
  4090. /** @internal */
  4091. this.defaultLanguageCode = null;
  4092. /** @internal */
  4093. this.customParameters = {};
  4094. }
  4095. /**
  4096. * Set the language gode.
  4097. *
  4098. * @param languageCode - language code
  4099. */
  4100. FederatedAuthProvider.prototype.setDefaultLanguage = function (languageCode) {
  4101. this.defaultLanguageCode = languageCode;
  4102. };
  4103. /**
  4104. * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
  4105. * operations.
  4106. *
  4107. * @remarks
  4108. * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
  4109. * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
  4110. *
  4111. * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
  4112. */
  4113. FederatedAuthProvider.prototype.setCustomParameters = function (customOAuthParameters) {
  4114. this.customParameters = customOAuthParameters;
  4115. return this;
  4116. };
  4117. /**
  4118. * Retrieve the current list of {@link CustomParameters}.
  4119. */
  4120. FederatedAuthProvider.prototype.getCustomParameters = function () {
  4121. return this.customParameters;
  4122. };
  4123. return FederatedAuthProvider;
  4124. }());
  4125. /**
  4126. * @license
  4127. * Copyright 2019 Google LLC
  4128. *
  4129. * Licensed under the Apache License, Version 2.0 (the "License");
  4130. * you may not use this file except in compliance with the License.
  4131. * You may obtain a copy of the License at
  4132. *
  4133. * http://www.apache.org/licenses/LICENSE-2.0
  4134. *
  4135. * Unless required by applicable law or agreed to in writing, software
  4136. * distributed under the License is distributed on an "AS IS" BASIS,
  4137. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4138. * See the License for the specific language governing permissions and
  4139. * limitations under the License.
  4140. */
  4141. /**
  4142. * Common code to all OAuth providers. This is separate from the
  4143. * {@link OAuthProvider} so that child providers (like
  4144. * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
  4145. * Instead, they rely on a static `credential` method.
  4146. */
  4147. var BaseOAuthProvider = /** @class */ (function (_super) {
  4148. tslib.__extends(BaseOAuthProvider, _super);
  4149. function BaseOAuthProvider() {
  4150. var _this = _super !== null && _super.apply(this, arguments) || this;
  4151. /** @internal */
  4152. _this.scopes = [];
  4153. return _this;
  4154. }
  4155. /**
  4156. * Add an OAuth scope to the credential.
  4157. *
  4158. * @param scope - Provider OAuth scope to add.
  4159. */
  4160. BaseOAuthProvider.prototype.addScope = function (scope) {
  4161. // If not already added, add scope to list.
  4162. if (!this.scopes.includes(scope)) {
  4163. this.scopes.push(scope);
  4164. }
  4165. return this;
  4166. };
  4167. /**
  4168. * Retrieve the current list of OAuth scopes.
  4169. */
  4170. BaseOAuthProvider.prototype.getScopes = function () {
  4171. return tslib.__spreadArray([], this.scopes, true);
  4172. };
  4173. return BaseOAuthProvider;
  4174. }(FederatedAuthProvider));
  4175. /**
  4176. * Provider for generating generic {@link OAuthCredential}.
  4177. *
  4178. * @example
  4179. * ```javascript
  4180. * // Sign in using a redirect.
  4181. * const provider = new OAuthProvider('google.com');
  4182. * // Start a sign in process for an unauthenticated user.
  4183. * provider.addScope('profile');
  4184. * provider.addScope('email');
  4185. * await signInWithRedirect(auth, provider);
  4186. * // This will trigger a full page redirect away from your app
  4187. *
  4188. * // After returning from the redirect when your app initializes you can obtain the result
  4189. * const result = await getRedirectResult(auth);
  4190. * if (result) {
  4191. * // This is the signed-in user
  4192. * const user = result.user;
  4193. * // This gives you a OAuth Access Token for the provider.
  4194. * const credential = provider.credentialFromResult(auth, result);
  4195. * const token = credential.accessToken;
  4196. * }
  4197. * ```
  4198. *
  4199. * @example
  4200. * ```javascript
  4201. * // Sign in using a popup.
  4202. * const provider = new OAuthProvider('google.com');
  4203. * provider.addScope('profile');
  4204. * provider.addScope('email');
  4205. * const result = await signInWithPopup(auth, provider);
  4206. *
  4207. * // The signed-in user info.
  4208. * const user = result.user;
  4209. * // This gives you a OAuth Access Token for the provider.
  4210. * const credential = provider.credentialFromResult(auth, result);
  4211. * const token = credential.accessToken;
  4212. * ```
  4213. * @public
  4214. */
  4215. var OAuthProvider = /** @class */ (function (_super) {
  4216. tslib.__extends(OAuthProvider, _super);
  4217. function OAuthProvider() {
  4218. return _super !== null && _super.apply(this, arguments) || this;
  4219. }
  4220. /**
  4221. * Creates an {@link OAuthCredential} from a JSON string or a plain object.
  4222. * @param json - A plain object or a JSON string
  4223. */
  4224. OAuthProvider.credentialFromJSON = function (json) {
  4225. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4226. _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4227. return OAuthCredential._fromParams(obj);
  4228. };
  4229. /**
  4230. * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
  4231. *
  4232. * @remarks
  4233. * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
  4234. * the raw nonce must match the nonce field in the ID token.
  4235. *
  4236. * @example
  4237. * ```javascript
  4238. * // `googleUser` from the onsuccess Google Sign In callback.
  4239. * // Initialize a generate OAuth provider with a `google.com` providerId.
  4240. * const provider = new OAuthProvider('google.com');
  4241. * const credential = provider.credential({
  4242. * idToken: googleUser.getAuthResponse().id_token,
  4243. * });
  4244. * const result = await signInWithCredential(credential);
  4245. * ```
  4246. *
  4247. * @param params - Either the options object containing the ID token, access token and raw nonce
  4248. * or the ID token string.
  4249. */
  4250. OAuthProvider.prototype.credential = function (params) {
  4251. return this._credential(tslib.__assign(tslib.__assign({}, params), { nonce: params.rawNonce }));
  4252. };
  4253. /** An internal credential method that accepts more permissive options */
  4254. OAuthProvider.prototype._credential = function (params) {
  4255. _assert(params.idToken || params.accessToken, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4256. // For OAuthCredential, sign in method is same as providerId.
  4257. return OAuthCredential._fromParams(tslib.__assign(tslib.__assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  4258. };
  4259. /**
  4260. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4261. *
  4262. * @param userCredential - The user credential.
  4263. */
  4264. OAuthProvider.credentialFromResult = function (userCredential) {
  4265. return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  4266. };
  4267. /**
  4268. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4269. * thrown during a sign-in, link, or reauthenticate operation.
  4270. *
  4271. * @param userCredential - The user credential.
  4272. */
  4273. OAuthProvider.credentialFromError = function (error) {
  4274. return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
  4275. };
  4276. OAuthProvider.oauthCredentialFromTaggedObject = function (_a) {
  4277. var tokenResponse = _a._tokenResponse;
  4278. if (!tokenResponse) {
  4279. return null;
  4280. }
  4281. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret, pendingToken = _b.pendingToken, nonce = _b.nonce, providerId = _b.providerId;
  4282. if (!oauthAccessToken &&
  4283. !oauthTokenSecret &&
  4284. !oauthIdToken &&
  4285. !pendingToken) {
  4286. return null;
  4287. }
  4288. if (!providerId) {
  4289. return null;
  4290. }
  4291. try {
  4292. return new OAuthProvider(providerId)._credential({
  4293. idToken: oauthIdToken,
  4294. accessToken: oauthAccessToken,
  4295. nonce: nonce,
  4296. pendingToken: pendingToken
  4297. });
  4298. }
  4299. catch (e) {
  4300. return null;
  4301. }
  4302. };
  4303. return OAuthProvider;
  4304. }(BaseOAuthProvider));
  4305. /**
  4306. * @license
  4307. * Copyright 2020 Google LLC
  4308. *
  4309. * Licensed under the Apache License, Version 2.0 (the "License");
  4310. * you may not use this file except in compliance with the License.
  4311. * You may obtain a copy of the License at
  4312. *
  4313. * http://www.apache.org/licenses/LICENSE-2.0
  4314. *
  4315. * Unless required by applicable law or agreed to in writing, software
  4316. * distributed under the License is distributed on an "AS IS" BASIS,
  4317. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4318. * See the License for the specific language governing permissions and
  4319. * limitations under the License.
  4320. */
  4321. /**
  4322. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
  4323. *
  4324. * @example
  4325. * ```javascript
  4326. * // Sign in using a redirect.
  4327. * const provider = new FacebookAuthProvider();
  4328. * // Start a sign in process for an unauthenticated user.
  4329. * provider.addScope('user_birthday');
  4330. * await signInWithRedirect(auth, provider);
  4331. * // This will trigger a full page redirect away from your app
  4332. *
  4333. * // After returning from the redirect when your app initializes you can obtain the result
  4334. * const result = await getRedirectResult(auth);
  4335. * if (result) {
  4336. * // This is the signed-in user
  4337. * const user = result.user;
  4338. * // This gives you a Facebook Access Token.
  4339. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4340. * const token = credential.accessToken;
  4341. * }
  4342. * ```
  4343. *
  4344. * @example
  4345. * ```javascript
  4346. * // Sign in using a popup.
  4347. * const provider = new FacebookAuthProvider();
  4348. * provider.addScope('user_birthday');
  4349. * const result = await signInWithPopup(auth, provider);
  4350. *
  4351. * // The signed-in user info.
  4352. * const user = result.user;
  4353. * // This gives you a Facebook Access Token.
  4354. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4355. * const token = credential.accessToken;
  4356. * ```
  4357. *
  4358. * @public
  4359. */
  4360. var FacebookAuthProvider = /** @class */ (function (_super) {
  4361. tslib.__extends(FacebookAuthProvider, _super);
  4362. function FacebookAuthProvider() {
  4363. return _super.call(this, "facebook.com" /* ProviderId.FACEBOOK */) || this;
  4364. }
  4365. /**
  4366. * Creates a credential for Facebook.
  4367. *
  4368. * @example
  4369. * ```javascript
  4370. * // `event` from the Facebook auth.authResponseChange callback.
  4371. * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
  4372. * const result = await signInWithCredential(credential);
  4373. * ```
  4374. *
  4375. * @param accessToken - Facebook access token.
  4376. */
  4377. FacebookAuthProvider.credential = function (accessToken) {
  4378. return OAuthCredential._fromParams({
  4379. providerId: FacebookAuthProvider.PROVIDER_ID,
  4380. signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
  4381. accessToken: accessToken
  4382. });
  4383. };
  4384. /**
  4385. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4386. *
  4387. * @param userCredential - The user credential.
  4388. */
  4389. FacebookAuthProvider.credentialFromResult = function (userCredential) {
  4390. return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  4391. };
  4392. /**
  4393. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4394. * thrown during a sign-in, link, or reauthenticate operation.
  4395. *
  4396. * @param userCredential - The user credential.
  4397. */
  4398. FacebookAuthProvider.credentialFromError = function (error) {
  4399. return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4400. };
  4401. FacebookAuthProvider.credentialFromTaggedObject = function (_a) {
  4402. var tokenResponse = _a._tokenResponse;
  4403. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4404. return null;
  4405. }
  4406. if (!tokenResponse.oauthAccessToken) {
  4407. return null;
  4408. }
  4409. try {
  4410. return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
  4411. }
  4412. catch (_b) {
  4413. return null;
  4414. }
  4415. };
  4416. /** Always set to {@link SignInMethod}.FACEBOOK. */
  4417. FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* SignInMethod.FACEBOOK */;
  4418. /** Always set to {@link ProviderId}.FACEBOOK. */
  4419. FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* ProviderId.FACEBOOK */;
  4420. return FacebookAuthProvider;
  4421. }(BaseOAuthProvider));
  4422. /**
  4423. * @license
  4424. * Copyright 2020 Google LLC
  4425. *
  4426. * Licensed under the Apache License, Version 2.0 (the "License");
  4427. * you may not use this file except in compliance with the License.
  4428. * You may obtain a copy of the License at
  4429. *
  4430. * http://www.apache.org/licenses/LICENSE-2.0
  4431. *
  4432. * Unless required by applicable law or agreed to in writing, software
  4433. * distributed under the License is distributed on an "AS IS" BASIS,
  4434. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4435. * See the License for the specific language governing permissions and
  4436. * limitations under the License.
  4437. */
  4438. /**
  4439. * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
  4440. *
  4441. * @example
  4442. * ```javascript
  4443. * // Sign in using a redirect.
  4444. * const provider = new GoogleAuthProvider();
  4445. * // Start a sign in process for an unauthenticated user.
  4446. * provider.addScope('profile');
  4447. * provider.addScope('email');
  4448. * await signInWithRedirect(auth, provider);
  4449. * // This will trigger a full page redirect away from your app
  4450. *
  4451. * // After returning from the redirect when your app initializes you can obtain the result
  4452. * const result = await getRedirectResult(auth);
  4453. * if (result) {
  4454. * // This is the signed-in user
  4455. * const user = result.user;
  4456. * // This gives you a Google Access Token.
  4457. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4458. * const token = credential.accessToken;
  4459. * }
  4460. * ```
  4461. *
  4462. * @example
  4463. * ```javascript
  4464. * // Sign in using a popup.
  4465. * const provider = new GoogleAuthProvider();
  4466. * provider.addScope('profile');
  4467. * provider.addScope('email');
  4468. * const result = await signInWithPopup(auth, provider);
  4469. *
  4470. * // The signed-in user info.
  4471. * const user = result.user;
  4472. * // This gives you a Google Access Token.
  4473. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4474. * const token = credential.accessToken;
  4475. * ```
  4476. *
  4477. * @public
  4478. */
  4479. var GoogleAuthProvider = /** @class */ (function (_super) {
  4480. tslib.__extends(GoogleAuthProvider, _super);
  4481. function GoogleAuthProvider() {
  4482. var _this = _super.call(this, "google.com" /* ProviderId.GOOGLE */) || this;
  4483. _this.addScope('profile');
  4484. return _this;
  4485. }
  4486. /**
  4487. * Creates a credential for Google. At least one of ID token and access token is required.
  4488. *
  4489. * @example
  4490. * ```javascript
  4491. * // \`googleUser\` from the onsuccess Google Sign In callback.
  4492. * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
  4493. * const result = await signInWithCredential(credential);
  4494. * ```
  4495. *
  4496. * @param idToken - Google ID token.
  4497. * @param accessToken - Google access token.
  4498. */
  4499. GoogleAuthProvider.credential = function (idToken, accessToken) {
  4500. return OAuthCredential._fromParams({
  4501. providerId: GoogleAuthProvider.PROVIDER_ID,
  4502. signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
  4503. idToken: idToken,
  4504. accessToken: accessToken
  4505. });
  4506. };
  4507. /**
  4508. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4509. *
  4510. * @param userCredential - The user credential.
  4511. */
  4512. GoogleAuthProvider.credentialFromResult = function (userCredential) {
  4513. return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  4514. };
  4515. /**
  4516. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4517. * thrown during a sign-in, link, or reauthenticate operation.
  4518. *
  4519. * @param userCredential - The user credential.
  4520. */
  4521. GoogleAuthProvider.credentialFromError = function (error) {
  4522. return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4523. };
  4524. GoogleAuthProvider.credentialFromTaggedObject = function (_a) {
  4525. var tokenResponse = _a._tokenResponse;
  4526. if (!tokenResponse) {
  4527. return null;
  4528. }
  4529. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken;
  4530. if (!oauthIdToken && !oauthAccessToken) {
  4531. // This could be an oauth 1 credential or a phone credential
  4532. return null;
  4533. }
  4534. try {
  4535. return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
  4536. }
  4537. catch (_c) {
  4538. return null;
  4539. }
  4540. };
  4541. /** Always set to {@link SignInMethod}.GOOGLE. */
  4542. GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* SignInMethod.GOOGLE */;
  4543. /** Always set to {@link ProviderId}.GOOGLE. */
  4544. GoogleAuthProvider.PROVIDER_ID = "google.com" /* ProviderId.GOOGLE */;
  4545. return GoogleAuthProvider;
  4546. }(BaseOAuthProvider));
  4547. /**
  4548. * @license
  4549. * Copyright 2020 Google LLC
  4550. *
  4551. * Licensed under the Apache License, Version 2.0 (the "License");
  4552. * you may not use this file except in compliance with the License.
  4553. * You may obtain a copy of the License at
  4554. *
  4555. * http://www.apache.org/licenses/LICENSE-2.0
  4556. *
  4557. * Unless required by applicable law or agreed to in writing, software
  4558. * distributed under the License is distributed on an "AS IS" BASIS,
  4559. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4560. * See the License for the specific language governing permissions and
  4561. * limitations under the License.
  4562. */
  4563. /**
  4564. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
  4565. *
  4566. * @remarks
  4567. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
  4568. * the {@link signInWithPopup} handler:
  4569. *
  4570. * @example
  4571. * ```javascript
  4572. * // Sign in using a redirect.
  4573. * const provider = new GithubAuthProvider();
  4574. * // Start a sign in process for an unauthenticated user.
  4575. * provider.addScope('repo');
  4576. * await signInWithRedirect(auth, provider);
  4577. * // This will trigger a full page redirect away from your app
  4578. *
  4579. * // After returning from the redirect when your app initializes you can obtain the result
  4580. * const result = await getRedirectResult(auth);
  4581. * if (result) {
  4582. * // This is the signed-in user
  4583. * const user = result.user;
  4584. * // This gives you a Github Access Token.
  4585. * const credential = GithubAuthProvider.credentialFromResult(result);
  4586. * const token = credential.accessToken;
  4587. * }
  4588. * ```
  4589. *
  4590. * @example
  4591. * ```javascript
  4592. * // Sign in using a popup.
  4593. * const provider = new GithubAuthProvider();
  4594. * provider.addScope('repo');
  4595. * const result = await signInWithPopup(auth, provider);
  4596. *
  4597. * // The signed-in user info.
  4598. * const user = result.user;
  4599. * // This gives you a Github Access Token.
  4600. * const credential = GithubAuthProvider.credentialFromResult(result);
  4601. * const token = credential.accessToken;
  4602. * ```
  4603. * @public
  4604. */
  4605. var GithubAuthProvider = /** @class */ (function (_super) {
  4606. tslib.__extends(GithubAuthProvider, _super);
  4607. function GithubAuthProvider() {
  4608. return _super.call(this, "github.com" /* ProviderId.GITHUB */) || this;
  4609. }
  4610. /**
  4611. * Creates a credential for Github.
  4612. *
  4613. * @param accessToken - Github access token.
  4614. */
  4615. GithubAuthProvider.credential = function (accessToken) {
  4616. return OAuthCredential._fromParams({
  4617. providerId: GithubAuthProvider.PROVIDER_ID,
  4618. signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
  4619. accessToken: accessToken
  4620. });
  4621. };
  4622. /**
  4623. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4624. *
  4625. * @param userCredential - The user credential.
  4626. */
  4627. GithubAuthProvider.credentialFromResult = function (userCredential) {
  4628. return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  4629. };
  4630. /**
  4631. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4632. * thrown during a sign-in, link, or reauthenticate operation.
  4633. *
  4634. * @param userCredential - The user credential.
  4635. */
  4636. GithubAuthProvider.credentialFromError = function (error) {
  4637. return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4638. };
  4639. GithubAuthProvider.credentialFromTaggedObject = function (_a) {
  4640. var tokenResponse = _a._tokenResponse;
  4641. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4642. return null;
  4643. }
  4644. if (!tokenResponse.oauthAccessToken) {
  4645. return null;
  4646. }
  4647. try {
  4648. return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
  4649. }
  4650. catch (_b) {
  4651. return null;
  4652. }
  4653. };
  4654. /** Always set to {@link SignInMethod}.GITHUB. */
  4655. GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* SignInMethod.GITHUB */;
  4656. /** Always set to {@link ProviderId}.GITHUB. */
  4657. GithubAuthProvider.PROVIDER_ID = "github.com" /* ProviderId.GITHUB */;
  4658. return GithubAuthProvider;
  4659. }(BaseOAuthProvider));
  4660. /**
  4661. * @license
  4662. * Copyright 2020 Google LLC
  4663. *
  4664. * Licensed under the Apache License, Version 2.0 (the "License");
  4665. * you may not use this file except in compliance with the License.
  4666. * You may obtain a copy of the License at
  4667. *
  4668. * http://www.apache.org/licenses/LICENSE-2.0
  4669. *
  4670. * Unless required by applicable law or agreed to in writing, software
  4671. * distributed under the License is distributed on an "AS IS" BASIS,
  4672. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4673. * See the License for the specific language governing permissions and
  4674. * limitations under the License.
  4675. */
  4676. var IDP_REQUEST_URI = 'http://localhost';
  4677. /**
  4678. * @public
  4679. */
  4680. var SAMLAuthCredential = /** @class */ (function (_super) {
  4681. tslib.__extends(SAMLAuthCredential, _super);
  4682. /** @internal */
  4683. function SAMLAuthCredential(providerId, pendingToken) {
  4684. var _this = _super.call(this, providerId, providerId) || this;
  4685. _this.pendingToken = pendingToken;
  4686. return _this;
  4687. }
  4688. /** @internal */
  4689. SAMLAuthCredential.prototype._getIdTokenResponse = function (auth) {
  4690. var request = this.buildRequest();
  4691. return signInWithIdp(auth, request);
  4692. };
  4693. /** @internal */
  4694. SAMLAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  4695. var request = this.buildRequest();
  4696. request.idToken = idToken;
  4697. return signInWithIdp(auth, request);
  4698. };
  4699. /** @internal */
  4700. SAMLAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  4701. var request = this.buildRequest();
  4702. request.autoCreate = false;
  4703. return signInWithIdp(auth, request);
  4704. };
  4705. /** {@inheritdoc AuthCredential.toJSON} */
  4706. SAMLAuthCredential.prototype.toJSON = function () {
  4707. return {
  4708. signInMethod: this.signInMethod,
  4709. providerId: this.providerId,
  4710. pendingToken: this.pendingToken
  4711. };
  4712. };
  4713. /**
  4714. * Static method to deserialize a JSON representation of an object into an
  4715. * {@link AuthCredential}.
  4716. *
  4717. * @param json - Input can be either Object or the stringified representation of the object.
  4718. * When string is provided, JSON.parse would be called first.
  4719. *
  4720. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  4721. */
  4722. SAMLAuthCredential.fromJSON = function (json) {
  4723. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4724. var providerId = obj.providerId, signInMethod = obj.signInMethod, pendingToken = obj.pendingToken;
  4725. if (!providerId ||
  4726. !signInMethod ||
  4727. !pendingToken ||
  4728. providerId !== signInMethod) {
  4729. return null;
  4730. }
  4731. return new SAMLAuthCredential(providerId, pendingToken);
  4732. };
  4733. /**
  4734. * Helper static method to avoid exposing the constructor to end users.
  4735. *
  4736. * @internal
  4737. */
  4738. SAMLAuthCredential._create = function (providerId, pendingToken) {
  4739. return new SAMLAuthCredential(providerId, pendingToken);
  4740. };
  4741. SAMLAuthCredential.prototype.buildRequest = function () {
  4742. return {
  4743. requestUri: IDP_REQUEST_URI,
  4744. returnSecureToken: true,
  4745. pendingToken: this.pendingToken
  4746. };
  4747. };
  4748. return SAMLAuthCredential;
  4749. }(AuthCredential));
  4750. /**
  4751. * @license
  4752. * Copyright 2020 Google LLC
  4753. *
  4754. * Licensed under the Apache License, Version 2.0 (the "License");
  4755. * you may not use this file except in compliance with the License.
  4756. * You may obtain a copy of the License at
  4757. *
  4758. * http://www.apache.org/licenses/LICENSE-2.0
  4759. *
  4760. * Unless required by applicable law or agreed to in writing, software
  4761. * distributed under the License is distributed on an "AS IS" BASIS,
  4762. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4763. * See the License for the specific language governing permissions and
  4764. * limitations under the License.
  4765. */
  4766. var SAML_PROVIDER_PREFIX = 'saml.';
  4767. /**
  4768. * An {@link AuthProvider} for SAML.
  4769. *
  4770. * @public
  4771. */
  4772. var SAMLAuthProvider = /** @class */ (function (_super) {
  4773. tslib.__extends(SAMLAuthProvider, _super);
  4774. /**
  4775. * Constructor. The providerId must start with "saml."
  4776. * @param providerId - SAML provider ID.
  4777. */
  4778. function SAMLAuthProvider(providerId) {
  4779. _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4780. return _super.call(this, providerId) || this;
  4781. }
  4782. /**
  4783. * Generates an {@link AuthCredential} from a {@link UserCredential} after a
  4784. * successful SAML flow completes.
  4785. *
  4786. * @remarks
  4787. *
  4788. * For example, to get an {@link AuthCredential}, you could write the
  4789. * following code:
  4790. *
  4791. * ```js
  4792. * const userCredential = await signInWithPopup(auth, samlProvider);
  4793. * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
  4794. * ```
  4795. *
  4796. * @param userCredential - The user credential.
  4797. */
  4798. SAMLAuthProvider.credentialFromResult = function (userCredential) {
  4799. return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  4800. };
  4801. /**
  4802. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4803. * thrown during a sign-in, link, or reauthenticate operation.
  4804. *
  4805. * @param userCredential - The user credential.
  4806. */
  4807. SAMLAuthProvider.credentialFromError = function (error) {
  4808. return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
  4809. };
  4810. /**
  4811. * Creates an {@link AuthCredential} from a JSON string or a plain object.
  4812. * @param json - A plain object or a JSON string
  4813. */
  4814. SAMLAuthProvider.credentialFromJSON = function (json) {
  4815. var credential = SAMLAuthCredential.fromJSON(json);
  4816. _assert(credential, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4817. return credential;
  4818. };
  4819. SAMLAuthProvider.samlCredentialFromTaggedObject = function (_a) {
  4820. var tokenResponse = _a._tokenResponse;
  4821. if (!tokenResponse) {
  4822. return null;
  4823. }
  4824. var _b = tokenResponse, pendingToken = _b.pendingToken, providerId = _b.providerId;
  4825. if (!pendingToken || !providerId) {
  4826. return null;
  4827. }
  4828. try {
  4829. return SAMLAuthCredential._create(providerId, pendingToken);
  4830. }
  4831. catch (e) {
  4832. return null;
  4833. }
  4834. };
  4835. return SAMLAuthProvider;
  4836. }(FederatedAuthProvider));
  4837. /**
  4838. * @license
  4839. * Copyright 2020 Google LLC
  4840. *
  4841. * Licensed under the Apache License, Version 2.0 (the "License");
  4842. * you may not use this file except in compliance with the License.
  4843. * You may obtain a copy of the License at
  4844. *
  4845. * http://www.apache.org/licenses/LICENSE-2.0
  4846. *
  4847. * Unless required by applicable law or agreed to in writing, software
  4848. * distributed under the License is distributed on an "AS IS" BASIS,
  4849. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4850. * See the License for the specific language governing permissions and
  4851. * limitations under the License.
  4852. */
  4853. /**
  4854. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
  4855. *
  4856. * @example
  4857. * ```javascript
  4858. * // Sign in using a redirect.
  4859. * const provider = new TwitterAuthProvider();
  4860. * // Start a sign in process for an unauthenticated user.
  4861. * await signInWithRedirect(auth, provider);
  4862. * // This will trigger a full page redirect away from your app
  4863. *
  4864. * // After returning from the redirect when your app initializes you can obtain the result
  4865. * const result = await getRedirectResult(auth);
  4866. * if (result) {
  4867. * // This is the signed-in user
  4868. * const user = result.user;
  4869. * // This gives you a Twitter Access Token and Secret.
  4870. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4871. * const token = credential.accessToken;
  4872. * const secret = credential.secret;
  4873. * }
  4874. * ```
  4875. *
  4876. * @example
  4877. * ```javascript
  4878. * // Sign in using a popup.
  4879. * const provider = new TwitterAuthProvider();
  4880. * const result = await signInWithPopup(auth, provider);
  4881. *
  4882. * // The signed-in user info.
  4883. * const user = result.user;
  4884. * // This gives you a Twitter Access Token and Secret.
  4885. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4886. * const token = credential.accessToken;
  4887. * const secret = credential.secret;
  4888. * ```
  4889. *
  4890. * @public
  4891. */
  4892. var TwitterAuthProvider = /** @class */ (function (_super) {
  4893. tslib.__extends(TwitterAuthProvider, _super);
  4894. function TwitterAuthProvider() {
  4895. return _super.call(this, "twitter.com" /* ProviderId.TWITTER */) || this;
  4896. }
  4897. /**
  4898. * Creates a credential for Twitter.
  4899. *
  4900. * @param token - Twitter access token.
  4901. * @param secret - Twitter secret.
  4902. */
  4903. TwitterAuthProvider.credential = function (token, secret) {
  4904. return OAuthCredential._fromParams({
  4905. providerId: TwitterAuthProvider.PROVIDER_ID,
  4906. signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
  4907. oauthToken: token,
  4908. oauthTokenSecret: secret
  4909. });
  4910. };
  4911. /**
  4912. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4913. *
  4914. * @param userCredential - The user credential.
  4915. */
  4916. TwitterAuthProvider.credentialFromResult = function (userCredential) {
  4917. return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  4918. };
  4919. /**
  4920. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4921. * thrown during a sign-in, link, or reauthenticate operation.
  4922. *
  4923. * @param userCredential - The user credential.
  4924. */
  4925. TwitterAuthProvider.credentialFromError = function (error) {
  4926. return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4927. };
  4928. TwitterAuthProvider.credentialFromTaggedObject = function (_a) {
  4929. var tokenResponse = _a._tokenResponse;
  4930. if (!tokenResponse) {
  4931. return null;
  4932. }
  4933. var _b = tokenResponse, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret;
  4934. if (!oauthAccessToken || !oauthTokenSecret) {
  4935. return null;
  4936. }
  4937. try {
  4938. return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
  4939. }
  4940. catch (_c) {
  4941. return null;
  4942. }
  4943. };
  4944. /** Always set to {@link SignInMethod}.TWITTER. */
  4945. TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* SignInMethod.TWITTER */;
  4946. /** Always set to {@link ProviderId}.TWITTER. */
  4947. TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* ProviderId.TWITTER */;
  4948. return TwitterAuthProvider;
  4949. }(BaseOAuthProvider));
  4950. /**
  4951. * @license
  4952. * Copyright 2020 Google LLC
  4953. *
  4954. * Licensed under the Apache License, Version 2.0 (the "License");
  4955. * you may not use this file except in compliance with the License.
  4956. * You may obtain a copy of the License at
  4957. *
  4958. * http://www.apache.org/licenses/LICENSE-2.0
  4959. *
  4960. * Unless required by applicable law or agreed to in writing, software
  4961. * distributed under the License is distributed on an "AS IS" BASIS,
  4962. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4963. * See the License for the specific language governing permissions and
  4964. * limitations under the License.
  4965. */
  4966. function signUp(auth, request) {
  4967. return tslib.__awaiter(this, void 0, void 0, function () {
  4968. return tslib.__generator(this, function (_a) {
  4969. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signUp" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request))];
  4970. });
  4971. });
  4972. }
  4973. /**
  4974. * @license
  4975. * Copyright 2020 Google LLC
  4976. *
  4977. * Licensed under the Apache License, Version 2.0 (the "License");
  4978. * you may not use this file except in compliance with the License.
  4979. * You may obtain a copy of the License at
  4980. *
  4981. * http://www.apache.org/licenses/LICENSE-2.0
  4982. *
  4983. * Unless required by applicable law or agreed to in writing, software
  4984. * distributed under the License is distributed on an "AS IS" BASIS,
  4985. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4986. * See the License for the specific language governing permissions and
  4987. * limitations under the License.
  4988. */
  4989. var UserCredentialImpl = /** @class */ (function () {
  4990. function UserCredentialImpl(params) {
  4991. this.user = params.user;
  4992. this.providerId = params.providerId;
  4993. this._tokenResponse = params._tokenResponse;
  4994. this.operationType = params.operationType;
  4995. }
  4996. UserCredentialImpl._fromIdTokenResponse = function (auth, operationType, idTokenResponse, isAnonymous) {
  4997. if (isAnonymous === void 0) { isAnonymous = false; }
  4998. return tslib.__awaiter(this, void 0, void 0, function () {
  4999. var user, providerId, userCred;
  5000. return tslib.__generator(this, function (_a) {
  5001. switch (_a.label) {
  5002. case 0: return [4 /*yield*/, UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous)];
  5003. case 1:
  5004. user = _a.sent();
  5005. providerId = providerIdForResponse(idTokenResponse);
  5006. userCred = new UserCredentialImpl({
  5007. user: user,
  5008. providerId: providerId,
  5009. _tokenResponse: idTokenResponse,
  5010. operationType: operationType
  5011. });
  5012. return [2 /*return*/, userCred];
  5013. }
  5014. });
  5015. });
  5016. };
  5017. UserCredentialImpl._forOperation = function (user, operationType, response) {
  5018. return tslib.__awaiter(this, void 0, void 0, function () {
  5019. var providerId;
  5020. return tslib.__generator(this, function (_a) {
  5021. switch (_a.label) {
  5022. case 0: return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  5023. case 1:
  5024. _a.sent();
  5025. providerId = providerIdForResponse(response);
  5026. return [2 /*return*/, new UserCredentialImpl({
  5027. user: user,
  5028. providerId: providerId,
  5029. _tokenResponse: response,
  5030. operationType: operationType
  5031. })];
  5032. }
  5033. });
  5034. });
  5035. };
  5036. return UserCredentialImpl;
  5037. }());
  5038. function providerIdForResponse(response) {
  5039. if (response.providerId) {
  5040. return response.providerId;
  5041. }
  5042. if ('phoneNumber' in response) {
  5043. return "phone" /* ProviderId.PHONE */;
  5044. }
  5045. return null;
  5046. }
  5047. /**
  5048. * @license
  5049. * Copyright 2020 Google LLC
  5050. *
  5051. * Licensed under the Apache License, Version 2.0 (the "License");
  5052. * you may not use this file except in compliance with the License.
  5053. * You may obtain a copy of the License at
  5054. *
  5055. * http://www.apache.org/licenses/LICENSE-2.0
  5056. *
  5057. * Unless required by applicable law or agreed to in writing, software
  5058. * distributed under the License is distributed on an "AS IS" BASIS,
  5059. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5060. * See the License for the specific language governing permissions and
  5061. * limitations under the License.
  5062. */
  5063. /**
  5064. * Asynchronously signs in as an anonymous user.
  5065. *
  5066. * @remarks
  5067. * If there is already an anonymous user signed in, that user will be returned; otherwise, a
  5068. * new anonymous user identity will be created and returned.
  5069. *
  5070. * @param auth - The {@link Auth} instance.
  5071. *
  5072. * @public
  5073. */
  5074. function signInAnonymously(auth) {
  5075. var _a;
  5076. return tslib.__awaiter(this, void 0, void 0, function () {
  5077. var authInternal, response, userCredential;
  5078. return tslib.__generator(this, function (_b) {
  5079. switch (_b.label) {
  5080. case 0:
  5081. authInternal = _castAuth(auth);
  5082. return [4 /*yield*/, authInternal._initializationPromise];
  5083. case 1:
  5084. _b.sent();
  5085. if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
  5086. // If an anonymous user is already signed in, no need to sign them in again.
  5087. return [2 /*return*/, new UserCredentialImpl({
  5088. user: authInternal.currentUser,
  5089. providerId: null,
  5090. operationType: "signIn" /* OperationType.SIGN_IN */
  5091. })];
  5092. }
  5093. return [4 /*yield*/, signUp(authInternal, {
  5094. returnSecureToken: true
  5095. })];
  5096. case 2:
  5097. response = _b.sent();
  5098. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response, true)];
  5099. case 3:
  5100. userCredential = _b.sent();
  5101. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  5102. case 4:
  5103. _b.sent();
  5104. return [2 /*return*/, userCredential];
  5105. }
  5106. });
  5107. });
  5108. }
  5109. /**
  5110. * @license
  5111. * Copyright 2020 Google LLC
  5112. *
  5113. * Licensed under the Apache License, Version 2.0 (the "License");
  5114. * you may not use this file except in compliance with the License.
  5115. * You may obtain a copy of the License at
  5116. *
  5117. * http://www.apache.org/licenses/LICENSE-2.0
  5118. *
  5119. * Unless required by applicable law or agreed to in writing, software
  5120. * distributed under the License is distributed on an "AS IS" BASIS,
  5121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5122. * See the License for the specific language governing permissions and
  5123. * limitations under the License.
  5124. */
  5125. var MultiFactorError = /** @class */ (function (_super) {
  5126. tslib.__extends(MultiFactorError, _super);
  5127. function MultiFactorError(auth, error, operationType, user) {
  5128. var _this = this;
  5129. var _a;
  5130. _this = _super.call(this, error.code, error.message) || this;
  5131. _this.operationType = operationType;
  5132. _this.user = user;
  5133. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  5134. Object.setPrototypeOf(_this, MultiFactorError.prototype);
  5135. _this.customData = {
  5136. appName: auth.name,
  5137. tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
  5138. _serverResponse: error.customData._serverResponse,
  5139. operationType: operationType
  5140. };
  5141. return _this;
  5142. }
  5143. MultiFactorError._fromErrorAndOperation = function (auth, error, operationType, user) {
  5144. return new MultiFactorError(auth, error, operationType, user);
  5145. };
  5146. return MultiFactorError;
  5147. }(util.FirebaseError));
  5148. function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  5149. var idTokenProvider = operationType === "reauthenticate" /* OperationType.REAUTHENTICATE */
  5150. ? credential._getReauthenticationResolver(auth)
  5151. : credential._getIdTokenResponse(auth);
  5152. return idTokenProvider.catch(function (error) {
  5153. if (error.code === "auth/".concat("multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */)) {
  5154. throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
  5155. }
  5156. throw error;
  5157. });
  5158. }
  5159. /**
  5160. * @license
  5161. * Copyright 2020 Google LLC
  5162. *
  5163. * Licensed under the Apache License, Version 2.0 (the "License");
  5164. * you may not use this file except in compliance with the License.
  5165. * You may obtain a copy of the License at
  5166. *
  5167. * http://www.apache.org/licenses/LICENSE-2.0
  5168. *
  5169. * Unless required by applicable law or agreed to in writing, software
  5170. * distributed under the License is distributed on an "AS IS" BASIS,
  5171. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5172. * See the License for the specific language governing permissions and
  5173. * limitations under the License.
  5174. */
  5175. /**
  5176. * Takes a set of UserInfo provider data and converts it to a set of names
  5177. */
  5178. function providerDataAsNames(providerData) {
  5179. return new Set(providerData
  5180. .map(function (_a) {
  5181. var providerId = _a.providerId;
  5182. return providerId;
  5183. })
  5184. .filter(function (pid) { return !!pid; }));
  5185. }
  5186. /**
  5187. * @license
  5188. * Copyright 2019 Google LLC
  5189. *
  5190. * Licensed under the Apache License, Version 2.0 (the "License");
  5191. * you may not use this file except in compliance with the License.
  5192. * You may obtain a copy of the License at
  5193. *
  5194. * http://www.apache.org/licenses/LICENSE-2.0
  5195. *
  5196. * Unless required by applicable law or agreed to in writing, software
  5197. * distributed under the License is distributed on an "AS IS" BASIS,
  5198. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5199. * See the License for the specific language governing permissions and
  5200. * limitations under the License.
  5201. */
  5202. /**
  5203. * Unlinks a provider from a user account.
  5204. *
  5205. * @param user - The user.
  5206. * @param providerId - The provider to unlink.
  5207. *
  5208. * @public
  5209. */
  5210. function unlink(user, providerId) {
  5211. return tslib.__awaiter(this, void 0, void 0, function () {
  5212. var userInternal, providerUserInfo, _a, _b, providersLeft;
  5213. var _c;
  5214. return tslib.__generator(this, function (_d) {
  5215. switch (_d.label) {
  5216. case 0:
  5217. userInternal = util.getModularInstance(user);
  5218. return [4 /*yield*/, _assertLinkedStatus(true, userInternal, providerId)];
  5219. case 1:
  5220. _d.sent();
  5221. _a = deleteLinkedAccounts;
  5222. _b = [userInternal.auth];
  5223. _c = {};
  5224. return [4 /*yield*/, userInternal.getIdToken()];
  5225. case 2: return [4 /*yield*/, _a.apply(void 0, _b.concat([(_c.idToken = _d.sent(),
  5226. _c.deleteProvider = [providerId],
  5227. _c)]))];
  5228. case 3:
  5229. providerUserInfo = (_d.sent()).providerUserInfo;
  5230. providersLeft = providerDataAsNames(providerUserInfo || []);
  5231. userInternal.providerData = userInternal.providerData.filter(function (pd) {
  5232. return providersLeft.has(pd.providerId);
  5233. });
  5234. if (!providersLeft.has("phone" /* ProviderId.PHONE */)) {
  5235. userInternal.phoneNumber = null;
  5236. }
  5237. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  5238. case 4:
  5239. _d.sent();
  5240. return [2 /*return*/, userInternal];
  5241. }
  5242. });
  5243. });
  5244. }
  5245. function _link(user, credential, bypassAuthState) {
  5246. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5247. return tslib.__awaiter(this, void 0, void 0, function () {
  5248. var response, _a, _b, _c, _d, _e;
  5249. return tslib.__generator(this, function (_f) {
  5250. switch (_f.label) {
  5251. case 0:
  5252. _a = _logoutIfInvalidated;
  5253. _b = [user];
  5254. _d = (_c = credential)._linkToIdToken;
  5255. _e = [user.auth];
  5256. return [4 /*yield*/, user.getIdToken()];
  5257. case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_d.apply(_c, _e.concat([_f.sent()])),
  5258. bypassAuthState]))];
  5259. case 2:
  5260. response = _f.sent();
  5261. return [2 /*return*/, UserCredentialImpl._forOperation(user, "link" /* OperationType.LINK */, response)];
  5262. }
  5263. });
  5264. });
  5265. }
  5266. function _assertLinkedStatus(expected, user, provider) {
  5267. return tslib.__awaiter(this, void 0, void 0, function () {
  5268. var providerIds, code;
  5269. return tslib.__generator(this, function (_a) {
  5270. switch (_a.label) {
  5271. case 0: return [4 /*yield*/, _reloadWithoutSaving(user)];
  5272. case 1:
  5273. _a.sent();
  5274. providerIds = providerDataAsNames(user.providerData);
  5275. code = expected === false
  5276. ? "provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
  5277. : "no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */;
  5278. _assert(providerIds.has(provider) === expected, user.auth, code);
  5279. return [2 /*return*/];
  5280. }
  5281. });
  5282. });
  5283. }
  5284. /**
  5285. * @license
  5286. * Copyright 2019 Google LLC
  5287. *
  5288. * Licensed under the Apache License, Version 2.0 (the "License");
  5289. * you may not use this file except in compliance with the License.
  5290. * You may obtain a copy of the License at
  5291. *
  5292. * http://www.apache.org/licenses/LICENSE-2.0
  5293. *
  5294. * Unless required by applicable law or agreed to in writing, software
  5295. * distributed under the License is distributed on an "AS IS" BASIS,
  5296. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5297. * See the License for the specific language governing permissions and
  5298. * limitations under the License.
  5299. */
  5300. function _reauthenticate(user, credential, bypassAuthState) {
  5301. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5302. return tslib.__awaiter(this, void 0, void 0, function () {
  5303. var auth, operationType, response, parsed, localId, e_1;
  5304. return tslib.__generator(this, function (_a) {
  5305. switch (_a.label) {
  5306. case 0:
  5307. auth = user.auth;
  5308. operationType = "reauthenticate" /* OperationType.REAUTHENTICATE */;
  5309. _a.label = 1;
  5310. case 1:
  5311. _a.trys.push([1, 3, , 4]);
  5312. return [4 /*yield*/, _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState)];
  5313. case 2:
  5314. response = _a.sent();
  5315. _assert(response.idToken, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5316. parsed = _parseToken(response.idToken);
  5317. _assert(parsed, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5318. localId = parsed.sub;
  5319. _assert(user.uid === localId, auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  5320. return [2 /*return*/, UserCredentialImpl._forOperation(user, operationType, response)];
  5321. case 3:
  5322. e_1 = _a.sent();
  5323. // Convert user deleted error into user mismatch
  5324. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) === "auth/".concat("user-not-found" /* AuthErrorCode.USER_DELETED */)) {
  5325. _fail(auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  5326. }
  5327. throw e_1;
  5328. case 4: return [2 /*return*/];
  5329. }
  5330. });
  5331. });
  5332. }
  5333. /**
  5334. * @license
  5335. * Copyright 2020 Google LLC
  5336. *
  5337. * Licensed under the Apache License, Version 2.0 (the "License");
  5338. * you may not use this file except in compliance with the License.
  5339. * You may obtain a copy of the License at
  5340. *
  5341. * http://www.apache.org/licenses/LICENSE-2.0
  5342. *
  5343. * Unless required by applicable law or agreed to in writing, software
  5344. * distributed under the License is distributed on an "AS IS" BASIS,
  5345. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5346. * See the License for the specific language governing permissions and
  5347. * limitations under the License.
  5348. */
  5349. function _signInWithCredential(auth, credential, bypassAuthState) {
  5350. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5351. return tslib.__awaiter(this, void 0, void 0, function () {
  5352. var operationType, response, userCredential;
  5353. return tslib.__generator(this, function (_a) {
  5354. switch (_a.label) {
  5355. case 0:
  5356. operationType = "signIn" /* OperationType.SIGN_IN */;
  5357. return [4 /*yield*/, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential)];
  5358. case 1:
  5359. response = _a.sent();
  5360. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, operationType, response)];
  5361. case 2:
  5362. userCredential = _a.sent();
  5363. if (!!bypassAuthState) return [3 /*break*/, 4];
  5364. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  5365. case 3:
  5366. _a.sent();
  5367. _a.label = 4;
  5368. case 4: return [2 /*return*/, userCredential];
  5369. }
  5370. });
  5371. });
  5372. }
  5373. /**
  5374. * Asynchronously signs in with the given credentials.
  5375. *
  5376. * @remarks
  5377. * An {@link AuthProvider} can be used to generate the credential.
  5378. *
  5379. * @param auth - The {@link Auth} instance.
  5380. * @param credential - The auth credential.
  5381. *
  5382. * @public
  5383. */
  5384. function signInWithCredential(auth, credential) {
  5385. return tslib.__awaiter(this, void 0, void 0, function () {
  5386. return tslib.__generator(this, function (_a) {
  5387. return [2 /*return*/, _signInWithCredential(_castAuth(auth), credential)];
  5388. });
  5389. });
  5390. }
  5391. /**
  5392. * Links the user account with the given credentials.
  5393. *
  5394. * @remarks
  5395. * An {@link AuthProvider} can be used to generate the credential.
  5396. *
  5397. * @param user - The user.
  5398. * @param credential - The auth credential.
  5399. *
  5400. * @public
  5401. */
  5402. function linkWithCredential(user, credential) {
  5403. return tslib.__awaiter(this, void 0, void 0, function () {
  5404. var userInternal;
  5405. return tslib.__generator(this, function (_a) {
  5406. switch (_a.label) {
  5407. case 0:
  5408. userInternal = util.getModularInstance(user);
  5409. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, credential.providerId)];
  5410. case 1:
  5411. _a.sent();
  5412. return [2 /*return*/, _link(userInternal, credential)];
  5413. }
  5414. });
  5415. });
  5416. }
  5417. /**
  5418. * Re-authenticates a user using a fresh credential.
  5419. *
  5420. * @remarks
  5421. * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
  5422. * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.
  5423. *
  5424. * @param user - The user.
  5425. * @param credential - The auth credential.
  5426. *
  5427. * @public
  5428. */
  5429. function reauthenticateWithCredential(user, credential) {
  5430. return tslib.__awaiter(this, void 0, void 0, function () {
  5431. return tslib.__generator(this, function (_a) {
  5432. return [2 /*return*/, _reauthenticate(util.getModularInstance(user), credential)];
  5433. });
  5434. });
  5435. }
  5436. /**
  5437. * @license
  5438. * Copyright 2020 Google LLC
  5439. *
  5440. * Licensed under the Apache License, Version 2.0 (the "License");
  5441. * you may not use this file except in compliance with the License.
  5442. * You may obtain a copy of the License at
  5443. *
  5444. * http://www.apache.org/licenses/LICENSE-2.0
  5445. *
  5446. * Unless required by applicable law or agreed to in writing, software
  5447. * distributed under the License is distributed on an "AS IS" BASIS,
  5448. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5449. * See the License for the specific language governing permissions and
  5450. * limitations under the License.
  5451. */
  5452. function signInWithCustomToken$1(auth, request) {
  5453. return tslib.__awaiter(this, void 0, void 0, function () {
  5454. return tslib.__generator(this, function (_a) {
  5455. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithCustomToken" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request))];
  5456. });
  5457. });
  5458. }
  5459. /**
  5460. * @license
  5461. * Copyright 2020 Google LLC
  5462. *
  5463. * Licensed under the Apache License, Version 2.0 (the "License");
  5464. * you may not use this file except in compliance with the License.
  5465. * You may obtain a copy of the License at
  5466. *
  5467. * http://www.apache.org/licenses/LICENSE-2.0
  5468. *
  5469. * Unless required by applicable law or agreed to in writing, software
  5470. * distributed under the License is distributed on an "AS IS" BASIS,
  5471. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5472. * See the License for the specific language governing permissions and
  5473. * limitations under the License.
  5474. */
  5475. /**
  5476. * Asynchronously signs in using a custom token.
  5477. *
  5478. * @remarks
  5479. * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
  5480. * be generated by an auth backend using the
  5481. * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
  5482. * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
  5483. *
  5484. * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
  5485. *
  5486. * @param auth - The {@link Auth} instance.
  5487. * @param customToken - The custom token to sign in with.
  5488. *
  5489. * @public
  5490. */
  5491. function signInWithCustomToken(auth, customToken) {
  5492. return tslib.__awaiter(this, void 0, void 0, function () {
  5493. var authInternal, response, cred;
  5494. return tslib.__generator(this, function (_a) {
  5495. switch (_a.label) {
  5496. case 0:
  5497. authInternal = _castAuth(auth);
  5498. return [4 /*yield*/, signInWithCustomToken$1(authInternal, {
  5499. token: customToken,
  5500. returnSecureToken: true
  5501. })];
  5502. case 1:
  5503. response = _a.sent();
  5504. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  5505. case 2:
  5506. cred = _a.sent();
  5507. return [4 /*yield*/, authInternal._updateCurrentUser(cred.user)];
  5508. case 3:
  5509. _a.sent();
  5510. return [2 /*return*/, cred];
  5511. }
  5512. });
  5513. });
  5514. }
  5515. /**
  5516. * @license
  5517. * Copyright 2020 Google LLC
  5518. *
  5519. * Licensed under the Apache License, Version 2.0 (the "License");
  5520. * you may not use this file except in compliance with the License.
  5521. * You may obtain a copy of the License at
  5522. *
  5523. * http://www.apache.org/licenses/LICENSE-2.0
  5524. *
  5525. * Unless required by applicable law or agreed to in writing, software
  5526. * distributed under the License is distributed on an "AS IS" BASIS,
  5527. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5528. * See the License for the specific language governing permissions and
  5529. * limitations under the License.
  5530. */
  5531. var MultiFactorInfoImpl = /** @class */ (function () {
  5532. function MultiFactorInfoImpl(factorId, response) {
  5533. this.factorId = factorId;
  5534. this.uid = response.mfaEnrollmentId;
  5535. this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
  5536. this.displayName = response.displayName;
  5537. }
  5538. MultiFactorInfoImpl._fromServerResponse = function (auth, enrollment) {
  5539. if ('phoneInfo' in enrollment) {
  5540. return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  5541. }
  5542. return _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5543. };
  5544. return MultiFactorInfoImpl;
  5545. }());
  5546. var PhoneMultiFactorInfoImpl = /** @class */ (function (_super) {
  5547. tslib.__extends(PhoneMultiFactorInfoImpl, _super);
  5548. function PhoneMultiFactorInfoImpl(response) {
  5549. var _this = _super.call(this, "phone" /* FactorId.PHONE */, response) || this;
  5550. _this.phoneNumber = response.phoneInfo;
  5551. return _this;
  5552. }
  5553. PhoneMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
  5554. return new PhoneMultiFactorInfoImpl(enrollment);
  5555. };
  5556. return PhoneMultiFactorInfoImpl;
  5557. }(MultiFactorInfoImpl));
  5558. /**
  5559. * @license
  5560. * Copyright 2020 Google LLC
  5561. *
  5562. * Licensed under the Apache License, Version 2.0 (the "License");
  5563. * you may not use this file except in compliance with the License.
  5564. * You may obtain a copy of the License at
  5565. *
  5566. * http://www.apache.org/licenses/LICENSE-2.0
  5567. *
  5568. * Unless required by applicable law or agreed to in writing, software
  5569. * distributed under the License is distributed on an "AS IS" BASIS,
  5570. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5571. * See the License for the specific language governing permissions and
  5572. * limitations under the License.
  5573. */
  5574. function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
  5575. var _a;
  5576. _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */);
  5577. _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
  5578. actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);
  5579. request.continueUrl = actionCodeSettings.url;
  5580. request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  5581. request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  5582. if (actionCodeSettings.iOS) {
  5583. _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);
  5584. request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  5585. }
  5586. if (actionCodeSettings.android) {
  5587. _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);
  5588. request.androidInstallApp = actionCodeSettings.android.installApp;
  5589. request.androidMinimumVersionCode =
  5590. actionCodeSettings.android.minimumVersion;
  5591. request.androidPackageName = actionCodeSettings.android.packageName;
  5592. }
  5593. }
  5594. /**
  5595. * @license
  5596. * Copyright 2020 Google LLC
  5597. *
  5598. * Licensed under the Apache License, Version 2.0 (the "License");
  5599. * you may not use this file except in compliance with the License.
  5600. * You may obtain a copy of the License at
  5601. *
  5602. * http://www.apache.org/licenses/LICENSE-2.0
  5603. *
  5604. * Unless required by applicable law or agreed to in writing, software
  5605. * distributed under the License is distributed on an "AS IS" BASIS,
  5606. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5607. * See the License for the specific language governing permissions and
  5608. * limitations under the License.
  5609. */
  5610. /**
  5611. * Sends a password reset email to the given email address.
  5612. *
  5613. * @remarks
  5614. * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
  5615. * the email sent to the user, along with the new password specified by the user.
  5616. *
  5617. * @example
  5618. * ```javascript
  5619. * const actionCodeSettings = {
  5620. * url: 'https://www.example.com/?email=user@example.com',
  5621. * iOS: {
  5622. * bundleId: 'com.example.ios'
  5623. * },
  5624. * android: {
  5625. * packageName: 'com.example.android',
  5626. * installApp: true,
  5627. * minimumVersion: '12'
  5628. * },
  5629. * handleCodeInApp: true
  5630. * };
  5631. * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
  5632. * // Obtain code from user.
  5633. * await confirmPasswordReset('user@example.com', code);
  5634. * ```
  5635. *
  5636. * @param auth - The {@link Auth} instance.
  5637. * @param email - The user's email address.
  5638. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5639. *
  5640. * @public
  5641. */
  5642. function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  5643. return tslib.__awaiter(this, void 0, void 0, function () {
  5644. var authModular, request;
  5645. return tslib.__generator(this, function (_a) {
  5646. switch (_a.label) {
  5647. case 0:
  5648. authModular = util.getModularInstance(auth);
  5649. request = {
  5650. requestType: "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */,
  5651. email: email
  5652. };
  5653. if (actionCodeSettings) {
  5654. _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
  5655. }
  5656. return [4 /*yield*/, sendPasswordResetEmail$1(authModular, request)];
  5657. case 1:
  5658. _a.sent();
  5659. return [2 /*return*/];
  5660. }
  5661. });
  5662. });
  5663. }
  5664. /**
  5665. * Completes the password reset process, given a confirmation code and new password.
  5666. *
  5667. * @param auth - The {@link Auth} instance.
  5668. * @param oobCode - A confirmation code sent to the user.
  5669. * @param newPassword - The new password.
  5670. *
  5671. * @public
  5672. */
  5673. function confirmPasswordReset(auth, oobCode, newPassword) {
  5674. return tslib.__awaiter(this, void 0, void 0, function () {
  5675. return tslib.__generator(this, function (_a) {
  5676. switch (_a.label) {
  5677. case 0: return [4 /*yield*/, resetPassword(util.getModularInstance(auth), {
  5678. oobCode: oobCode,
  5679. newPassword: newPassword
  5680. })];
  5681. case 1:
  5682. _a.sent();
  5683. return [2 /*return*/];
  5684. }
  5685. });
  5686. });
  5687. }
  5688. /**
  5689. * Applies a verification code sent to the user by email or other out-of-band mechanism.
  5690. *
  5691. * @param auth - The {@link Auth} instance.
  5692. * @param oobCode - A verification code sent to the user.
  5693. *
  5694. * @public
  5695. */
  5696. function applyActionCode(auth, oobCode) {
  5697. return tslib.__awaiter(this, void 0, void 0, function () {
  5698. return tslib.__generator(this, function (_a) {
  5699. switch (_a.label) {
  5700. case 0: return [4 /*yield*/, applyActionCode$1(util.getModularInstance(auth), { oobCode: oobCode })];
  5701. case 1:
  5702. _a.sent();
  5703. return [2 /*return*/];
  5704. }
  5705. });
  5706. });
  5707. }
  5708. /**
  5709. * Checks a verification code sent to the user by email or other out-of-band mechanism.
  5710. *
  5711. * @returns metadata about the code.
  5712. *
  5713. * @param auth - The {@link Auth} instance.
  5714. * @param oobCode - A verification code sent to the user.
  5715. *
  5716. * @public
  5717. */
  5718. function checkActionCode(auth, oobCode) {
  5719. return tslib.__awaiter(this, void 0, void 0, function () {
  5720. var authModular, response, operation, multiFactorInfo;
  5721. return tslib.__generator(this, function (_a) {
  5722. switch (_a.label) {
  5723. case 0:
  5724. authModular = util.getModularInstance(auth);
  5725. return [4 /*yield*/, resetPassword(authModular, { oobCode: oobCode })];
  5726. case 1:
  5727. response = _a.sent();
  5728. operation = response.requestType;
  5729. _assert(operation, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5730. switch (operation) {
  5731. case "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */:
  5732. break;
  5733. case "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:
  5734. _assert(response.newEmail, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5735. break;
  5736. case "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:
  5737. _assert(response.mfaInfo, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5738. // fall through
  5739. default:
  5740. _assert(response.email, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5741. }
  5742. multiFactorInfo = null;
  5743. if (response.mfaInfo) {
  5744. multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  5745. }
  5746. return [2 /*return*/, {
  5747. data: {
  5748. email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  5749. ? response.newEmail
  5750. : response.email) || null,
  5751. previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  5752. ? response.email
  5753. : response.newEmail) || null,
  5754. multiFactorInfo: multiFactorInfo
  5755. },
  5756. operation: operation
  5757. }];
  5758. }
  5759. });
  5760. });
  5761. }
  5762. /**
  5763. * Checks a password reset code sent to the user by email or other out-of-band mechanism.
  5764. *
  5765. * @returns the user's email address if valid.
  5766. *
  5767. * @param auth - The {@link Auth} instance.
  5768. * @param code - A verification code sent to the user.
  5769. *
  5770. * @public
  5771. */
  5772. function verifyPasswordResetCode(auth, code) {
  5773. return tslib.__awaiter(this, void 0, void 0, function () {
  5774. var data;
  5775. return tslib.__generator(this, function (_a) {
  5776. switch (_a.label) {
  5777. case 0: return [4 /*yield*/, checkActionCode(util.getModularInstance(auth), code)];
  5778. case 1:
  5779. data = (_a.sent()).data;
  5780. // Email should always be present since a code was sent to it
  5781. return [2 /*return*/, data.email];
  5782. }
  5783. });
  5784. });
  5785. }
  5786. /**
  5787. * Creates a new user account associated with the specified email address and password.
  5788. *
  5789. * @remarks
  5790. * On successful creation of the user account, this user will also be signed in to your application.
  5791. *
  5792. * User account creation can fail if the account already exists or the password is invalid.
  5793. *
  5794. * Note: The email address acts as a unique identifier for the user and enables an email-based
  5795. * password reset. This function will create a new user account and set the initial user password.
  5796. *
  5797. * @param auth - The {@link Auth} instance.
  5798. * @param email - The user's email address.
  5799. * @param password - The user's chosen password.
  5800. *
  5801. * @public
  5802. */
  5803. function createUserWithEmailAndPassword(auth, email, password) {
  5804. return tslib.__awaiter(this, void 0, void 0, function () {
  5805. var authInternal, response, userCredential;
  5806. return tslib.__generator(this, function (_a) {
  5807. switch (_a.label) {
  5808. case 0:
  5809. authInternal = _castAuth(auth);
  5810. return [4 /*yield*/, signUp(authInternal, {
  5811. returnSecureToken: true,
  5812. email: email,
  5813. password: password
  5814. })];
  5815. case 1:
  5816. response = _a.sent();
  5817. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  5818. case 2:
  5819. userCredential = _a.sent();
  5820. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  5821. case 3:
  5822. _a.sent();
  5823. return [2 /*return*/, userCredential];
  5824. }
  5825. });
  5826. });
  5827. }
  5828. /**
  5829. * Asynchronously signs in using an email and password.
  5830. *
  5831. * @remarks
  5832. * Fails with an error if the email address and password do not match.
  5833. *
  5834. * Note: The user's password is NOT the password used to access the user's email account. The
  5835. * email address serves as a unique identifier for the user, and the password is used to access
  5836. * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
  5837. *
  5838. * @param auth - The {@link Auth} instance.
  5839. * @param email - The users email address.
  5840. * @param password - The users password.
  5841. *
  5842. * @public
  5843. */
  5844. function signInWithEmailAndPassword(auth, email, password) {
  5845. return signInWithCredential(util.getModularInstance(auth), EmailAuthProvider.credential(email, password));
  5846. }
  5847. /**
  5848. * @license
  5849. * Copyright 2020 Google LLC
  5850. *
  5851. * Licensed under the Apache License, Version 2.0 (the "License");
  5852. * you may not use this file except in compliance with the License.
  5853. * You may obtain a copy of the License at
  5854. *
  5855. * http://www.apache.org/licenses/LICENSE-2.0
  5856. *
  5857. * Unless required by applicable law or agreed to in writing, software
  5858. * distributed under the License is distributed on an "AS IS" BASIS,
  5859. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5860. * See the License for the specific language governing permissions and
  5861. * limitations under the License.
  5862. */
  5863. /**
  5864. * Sends a sign-in email link to the user with the specified email.
  5865. *
  5866. * @remarks
  5867. * The sign-in operation has to always be completed in the app unlike other out of band email
  5868. * actions (password reset and email verifications). This is because, at the end of the flow,
  5869. * the user is expected to be signed in and their Auth state persisted within the app.
  5870. *
  5871. * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
  5872. * address and the email link supplied in the email sent to the user.
  5873. *
  5874. * @example
  5875. * ```javascript
  5876. * const actionCodeSettings = {
  5877. * url: 'https://www.example.com/?email=user@example.com',
  5878. * iOS: {
  5879. * bundleId: 'com.example.ios'
  5880. * },
  5881. * android: {
  5882. * packageName: 'com.example.android',
  5883. * installApp: true,
  5884. * minimumVersion: '12'
  5885. * },
  5886. * handleCodeInApp: true
  5887. * };
  5888. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5889. * // Obtain emailLink from the user.
  5890. * if(isSignInWithEmailLink(auth, emailLink)) {
  5891. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5892. * }
  5893. * ```
  5894. *
  5895. * @param authInternal - The {@link Auth} instance.
  5896. * @param email - The user's email address.
  5897. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5898. *
  5899. * @public
  5900. */
  5901. function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
  5902. return tslib.__awaiter(this, void 0, void 0, function () {
  5903. var authModular, request;
  5904. return tslib.__generator(this, function (_a) {
  5905. switch (_a.label) {
  5906. case 0:
  5907. authModular = util.getModularInstance(auth);
  5908. request = {
  5909. requestType: "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */,
  5910. email: email
  5911. };
  5912. _assert(actionCodeSettings.handleCodeInApp, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5913. if (actionCodeSettings) {
  5914. _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
  5915. }
  5916. return [4 /*yield*/, sendSignInLinkToEmail$1(authModular, request)];
  5917. case 1:
  5918. _a.sent();
  5919. return [2 /*return*/];
  5920. }
  5921. });
  5922. });
  5923. }
  5924. /**
  5925. * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
  5926. *
  5927. * @param auth - The {@link Auth} instance.
  5928. * @param emailLink - The link sent to the user's email address.
  5929. *
  5930. * @public
  5931. */
  5932. function isSignInWithEmailLink(auth, emailLink) {
  5933. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  5934. return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  5935. }
  5936. /**
  5937. * Asynchronously signs in using an email and sign-in email link.
  5938. *
  5939. * @remarks
  5940. * If no link is passed, the link is inferred from the current URL.
  5941. *
  5942. * Fails with an error if the email address is invalid or OTP in email link expires.
  5943. *
  5944. * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
  5945. *
  5946. * @example
  5947. * ```javascript
  5948. * const actionCodeSettings = {
  5949. * url: 'https://www.example.com/?email=user@example.com',
  5950. * iOS: {
  5951. * bundleId: 'com.example.ios'
  5952. * },
  5953. * android: {
  5954. * packageName: 'com.example.android',
  5955. * installApp: true,
  5956. * minimumVersion: '12'
  5957. * },
  5958. * handleCodeInApp: true
  5959. * };
  5960. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5961. * // Obtain emailLink from the user.
  5962. * if(isSignInWithEmailLink(auth, emailLink)) {
  5963. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5964. * }
  5965. * ```
  5966. *
  5967. * @param auth - The {@link Auth} instance.
  5968. * @param email - The user's email address.
  5969. * @param emailLink - The link sent to the user's email address.
  5970. *
  5971. * @public
  5972. */
  5973. function signInWithEmailLink(auth, email, emailLink) {
  5974. return tslib.__awaiter(this, void 0, void 0, function () {
  5975. var authModular, credential;
  5976. return tslib.__generator(this, function (_a) {
  5977. authModular = util.getModularInstance(auth);
  5978. credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  5979. // Check if the tenant ID in the email link matches the tenant ID on Auth
  5980. // instance.
  5981. _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  5982. return [2 /*return*/, signInWithCredential(authModular, credential)];
  5983. });
  5984. });
  5985. }
  5986. /**
  5987. * @license
  5988. * Copyright 2020 Google LLC
  5989. *
  5990. * Licensed under the Apache License, Version 2.0 (the "License");
  5991. * you may not use this file except in compliance with the License.
  5992. * You may obtain a copy of the License at
  5993. *
  5994. * http://www.apache.org/licenses/LICENSE-2.0
  5995. *
  5996. * Unless required by applicable law or agreed to in writing, software
  5997. * distributed under the License is distributed on an "AS IS" BASIS,
  5998. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5999. * See the License for the specific language governing permissions and
  6000. * limitations under the License.
  6001. */
  6002. function createAuthUri(auth, request) {
  6003. return tslib.__awaiter(this, void 0, void 0, function () {
  6004. return tslib.__generator(this, function (_a) {
  6005. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:createAuthUri" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request))];
  6006. });
  6007. });
  6008. }
  6009. /**
  6010. * @license
  6011. * Copyright 2020 Google LLC
  6012. *
  6013. * Licensed under the Apache License, Version 2.0 (the "License");
  6014. * you may not use this file except in compliance with the License.
  6015. * You may obtain a copy of the License at
  6016. *
  6017. * http://www.apache.org/licenses/LICENSE-2.0
  6018. *
  6019. * Unless required by applicable law or agreed to in writing, software
  6020. * distributed under the License is distributed on an "AS IS" BASIS,
  6021. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6022. * See the License for the specific language governing permissions and
  6023. * limitations under the License.
  6024. */
  6025. /**
  6026. * Gets the list of possible sign in methods for the given email address.
  6027. *
  6028. * @remarks
  6029. * This is useful to differentiate methods of sign-in for the same provider, eg.
  6030. * {@link EmailAuthProvider} which has 2 methods of sign-in,
  6031. * {@link SignInMethod}.EMAIL_PASSWORD and
  6032. * {@link SignInMethod}.EMAIL_LINK.
  6033. *
  6034. * @param auth - The {@link Auth} instance.
  6035. * @param email - The user's email address.
  6036. *
  6037. * @public
  6038. */
  6039. function fetchSignInMethodsForEmail(auth, email) {
  6040. return tslib.__awaiter(this, void 0, void 0, function () {
  6041. var continueUri, request, signinMethods;
  6042. return tslib.__generator(this, function (_a) {
  6043. switch (_a.label) {
  6044. case 0:
  6045. continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
  6046. request = {
  6047. identifier: email,
  6048. continueUri: continueUri
  6049. };
  6050. return [4 /*yield*/, createAuthUri(util.getModularInstance(auth), request)];
  6051. case 1:
  6052. signinMethods = (_a.sent()).signinMethods;
  6053. return [2 /*return*/, signinMethods || []];
  6054. }
  6055. });
  6056. });
  6057. }
  6058. /**
  6059. * Sends a verification email to a user.
  6060. *
  6061. * @remarks
  6062. * The verification process is completed by calling {@link applyActionCode}.
  6063. *
  6064. * @example
  6065. * ```javascript
  6066. * const actionCodeSettings = {
  6067. * url: 'https://www.example.com/?email=user@example.com',
  6068. * iOS: {
  6069. * bundleId: 'com.example.ios'
  6070. * },
  6071. * android: {
  6072. * packageName: 'com.example.android',
  6073. * installApp: true,
  6074. * minimumVersion: '12'
  6075. * },
  6076. * handleCodeInApp: true
  6077. * };
  6078. * await sendEmailVerification(user, actionCodeSettings);
  6079. * // Obtain code from the user.
  6080. * await applyActionCode(auth, code);
  6081. * ```
  6082. *
  6083. * @param user - The user.
  6084. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6085. *
  6086. * @public
  6087. */
  6088. function sendEmailVerification(user, actionCodeSettings) {
  6089. return tslib.__awaiter(this, void 0, void 0, function () {
  6090. var userInternal, idToken, request, email;
  6091. return tslib.__generator(this, function (_a) {
  6092. switch (_a.label) {
  6093. case 0:
  6094. userInternal = util.getModularInstance(user);
  6095. return [4 /*yield*/, user.getIdToken()];
  6096. case 1:
  6097. idToken = _a.sent();
  6098. request = {
  6099. requestType: "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */,
  6100. idToken: idToken
  6101. };
  6102. if (actionCodeSettings) {
  6103. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  6104. }
  6105. return [4 /*yield*/, sendEmailVerification$1(userInternal.auth, request)];
  6106. case 2:
  6107. email = (_a.sent()).email;
  6108. if (!(email !== user.email)) return [3 /*break*/, 4];
  6109. return [4 /*yield*/, user.reload()];
  6110. case 3:
  6111. _a.sent();
  6112. _a.label = 4;
  6113. case 4: return [2 /*return*/];
  6114. }
  6115. });
  6116. });
  6117. }
  6118. /**
  6119. * Sends a verification email to a new email address.
  6120. *
  6121. * @remarks
  6122. * The user's email will be updated to the new one after being verified.
  6123. *
  6124. * If you have a custom email action handler, you can complete the verification process by calling
  6125. * {@link applyActionCode}.
  6126. *
  6127. * @example
  6128. * ```javascript
  6129. * const actionCodeSettings = {
  6130. * url: 'https://www.example.com/?email=user@example.com',
  6131. * iOS: {
  6132. * bundleId: 'com.example.ios'
  6133. * },
  6134. * android: {
  6135. * packageName: 'com.example.android',
  6136. * installApp: true,
  6137. * minimumVersion: '12'
  6138. * },
  6139. * handleCodeInApp: true
  6140. * };
  6141. * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
  6142. * // Obtain code from the user.
  6143. * await applyActionCode(auth, code);
  6144. * ```
  6145. *
  6146. * @param user - The user.
  6147. * @param newEmail - The new email address to be verified before update.
  6148. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6149. *
  6150. * @public
  6151. */
  6152. function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  6153. return tslib.__awaiter(this, void 0, void 0, function () {
  6154. var userInternal, idToken, request, email;
  6155. return tslib.__generator(this, function (_a) {
  6156. switch (_a.label) {
  6157. case 0:
  6158. userInternal = util.getModularInstance(user);
  6159. return [4 /*yield*/, user.getIdToken()];
  6160. case 1:
  6161. idToken = _a.sent();
  6162. request = {
  6163. requestType: "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,
  6164. idToken: idToken,
  6165. newEmail: newEmail
  6166. };
  6167. if (actionCodeSettings) {
  6168. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  6169. }
  6170. return [4 /*yield*/, verifyAndChangeEmail(userInternal.auth, request)];
  6171. case 2:
  6172. email = (_a.sent()).email;
  6173. if (!(email !== user.email)) return [3 /*break*/, 4];
  6174. // If the local copy of the email on user is outdated, reload the
  6175. // user.
  6176. return [4 /*yield*/, user.reload()];
  6177. case 3:
  6178. // If the local copy of the email on user is outdated, reload the
  6179. // user.
  6180. _a.sent();
  6181. _a.label = 4;
  6182. case 4: return [2 /*return*/];
  6183. }
  6184. });
  6185. });
  6186. }
  6187. /**
  6188. * @license
  6189. * Copyright 2020 Google LLC
  6190. *
  6191. * Licensed under the Apache License, Version 2.0 (the "License");
  6192. * you may not use this file except in compliance with the License.
  6193. * You may obtain a copy of the License at
  6194. *
  6195. * http://www.apache.org/licenses/LICENSE-2.0
  6196. *
  6197. * Unless required by applicable law or agreed to in writing, software
  6198. * distributed under the License is distributed on an "AS IS" BASIS,
  6199. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6200. * See the License for the specific language governing permissions and
  6201. * limitations under the License.
  6202. */
  6203. function updateProfile$1(auth, request) {
  6204. return tslib.__awaiter(this, void 0, void 0, function () {
  6205. return tslib.__generator(this, function (_a) {
  6206. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  6207. });
  6208. });
  6209. }
  6210. /**
  6211. * @license
  6212. * Copyright 2020 Google LLC
  6213. *
  6214. * Licensed under the Apache License, Version 2.0 (the "License");
  6215. * you may not use this file except in compliance with the License.
  6216. * You may obtain a copy of the License at
  6217. *
  6218. * http://www.apache.org/licenses/LICENSE-2.0
  6219. *
  6220. * Unless required by applicable law or agreed to in writing, software
  6221. * distributed under the License is distributed on an "AS IS" BASIS,
  6222. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6223. * See the License for the specific language governing permissions and
  6224. * limitations under the License.
  6225. */
  6226. /**
  6227. * Updates a user's profile data.
  6228. *
  6229. * @param user - The user.
  6230. * @param profile - The profile's `displayName` and `photoURL` to update.
  6231. *
  6232. * @public
  6233. */
  6234. function updateProfile(user, _a) {
  6235. var displayName = _a.displayName, photoUrl = _a.photoURL;
  6236. return tslib.__awaiter(this, void 0, void 0, function () {
  6237. var userInternal, idToken, profileRequest, response, passwordProvider;
  6238. return tslib.__generator(this, function (_b) {
  6239. switch (_b.label) {
  6240. case 0:
  6241. if (displayName === undefined && photoUrl === undefined) {
  6242. return [2 /*return*/];
  6243. }
  6244. userInternal = util.getModularInstance(user);
  6245. return [4 /*yield*/, userInternal.getIdToken()];
  6246. case 1:
  6247. idToken = _b.sent();
  6248. profileRequest = {
  6249. idToken: idToken,
  6250. displayName: displayName,
  6251. photoUrl: photoUrl,
  6252. returnSecureToken: true
  6253. };
  6254. return [4 /*yield*/, _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest))];
  6255. case 2:
  6256. response = _b.sent();
  6257. userInternal.displayName = response.displayName || null;
  6258. userInternal.photoURL = response.photoUrl || null;
  6259. passwordProvider = userInternal.providerData.find(function (_a) {
  6260. var providerId = _a.providerId;
  6261. return providerId === "password" /* ProviderId.PASSWORD */;
  6262. });
  6263. if (passwordProvider) {
  6264. passwordProvider.displayName = userInternal.displayName;
  6265. passwordProvider.photoURL = userInternal.photoURL;
  6266. }
  6267. return [4 /*yield*/, userInternal._updateTokensIfNecessary(response)];
  6268. case 3:
  6269. _b.sent();
  6270. return [2 /*return*/];
  6271. }
  6272. });
  6273. });
  6274. }
  6275. /**
  6276. * Updates the user's email address.
  6277. *
  6278. * @remarks
  6279. * An email will be sent to the original email address (if it was set) that allows to revoke the
  6280. * email address change, in order to protect them from account hijacking.
  6281. *
  6282. * Important: this is a security sensitive operation that requires the user to have recently signed
  6283. * in. If this requirement isn't met, ask the user to authenticate again and then call
  6284. * {@link reauthenticateWithCredential}.
  6285. *
  6286. * @param user - The user.
  6287. * @param newEmail - The new email address.
  6288. *
  6289. * @public
  6290. */
  6291. function updateEmail(user, newEmail) {
  6292. return updateEmailOrPassword(util.getModularInstance(user), newEmail, null);
  6293. }
  6294. /**
  6295. * Updates the user's password.
  6296. *
  6297. * @remarks
  6298. * Important: this is a security sensitive operation that requires the user to have recently signed
  6299. * in. If this requirement isn't met, ask the user to authenticate again and then call
  6300. * {@link reauthenticateWithCredential}.
  6301. *
  6302. * @param user - The user.
  6303. * @param newPassword - The new password.
  6304. *
  6305. * @public
  6306. */
  6307. function updatePassword(user, newPassword) {
  6308. return updateEmailOrPassword(util.getModularInstance(user), null, newPassword);
  6309. }
  6310. function updateEmailOrPassword(user, email, password) {
  6311. return tslib.__awaiter(this, void 0, void 0, function () {
  6312. var auth, idToken, request, response;
  6313. return tslib.__generator(this, function (_a) {
  6314. switch (_a.label) {
  6315. case 0:
  6316. auth = user.auth;
  6317. return [4 /*yield*/, user.getIdToken()];
  6318. case 1:
  6319. idToken = _a.sent();
  6320. request = {
  6321. idToken: idToken,
  6322. returnSecureToken: true
  6323. };
  6324. if (email) {
  6325. request.email = email;
  6326. }
  6327. if (password) {
  6328. request.password = password;
  6329. }
  6330. return [4 /*yield*/, _logoutIfInvalidated(user, updateEmailPassword(auth, request))];
  6331. case 2:
  6332. response = _a.sent();
  6333. return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  6334. case 3:
  6335. _a.sent();
  6336. return [2 /*return*/];
  6337. }
  6338. });
  6339. });
  6340. }
  6341. /**
  6342. * @license
  6343. * Copyright 2019 Google LLC
  6344. *
  6345. * Licensed under the Apache License, Version 2.0 (the "License");
  6346. * you may not use this file except in compliance with the License.
  6347. * You may obtain a copy of the License at
  6348. *
  6349. * http://www.apache.org/licenses/LICENSE-2.0
  6350. *
  6351. * Unless required by applicable law or agreed to in writing, software
  6352. * distributed under the License is distributed on an "AS IS" BASIS,
  6353. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6354. * See the License for the specific language governing permissions and
  6355. * limitations under the License.
  6356. */
  6357. /**
  6358. * Parse the `AdditionalUserInfo` from the ID token response.
  6359. *
  6360. */
  6361. function _fromIdTokenResponse(idTokenResponse) {
  6362. var _a, _b;
  6363. if (!idTokenResponse) {
  6364. return null;
  6365. }
  6366. var providerId = idTokenResponse.providerId;
  6367. var profile = idTokenResponse.rawUserInfo
  6368. ? JSON.parse(idTokenResponse.rawUserInfo)
  6369. : {};
  6370. var isNewUser = idTokenResponse.isNewUser ||
  6371. idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* IdTokenResponseKind.SignupNewUser */;
  6372. if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
  6373. var signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
  6374. if (signInProvider) {
  6375. var filteredProviderId = signInProvider !== "anonymous" /* ProviderId.ANONYMOUS */ &&
  6376. signInProvider !== "custom" /* ProviderId.CUSTOM */
  6377. ? signInProvider
  6378. : null;
  6379. // Uses generic class in accordance with the legacy SDK.
  6380. return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
  6381. }
  6382. }
  6383. if (!providerId) {
  6384. return null;
  6385. }
  6386. switch (providerId) {
  6387. case "facebook.com" /* ProviderId.FACEBOOK */:
  6388. return new FacebookAdditionalUserInfo(isNewUser, profile);
  6389. case "github.com" /* ProviderId.GITHUB */:
  6390. return new GithubAdditionalUserInfo(isNewUser, profile);
  6391. case "google.com" /* ProviderId.GOOGLE */:
  6392. return new GoogleAdditionalUserInfo(isNewUser, profile);
  6393. case "twitter.com" /* ProviderId.TWITTER */:
  6394. return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
  6395. case "custom" /* ProviderId.CUSTOM */:
  6396. case "anonymous" /* ProviderId.ANONYMOUS */:
  6397. return new GenericAdditionalUserInfo(isNewUser, null);
  6398. default:
  6399. return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  6400. }
  6401. }
  6402. var GenericAdditionalUserInfo = /** @class */ (function () {
  6403. function GenericAdditionalUserInfo(isNewUser, providerId, profile) {
  6404. if (profile === void 0) { profile = {}; }
  6405. this.isNewUser = isNewUser;
  6406. this.providerId = providerId;
  6407. this.profile = profile;
  6408. }
  6409. return GenericAdditionalUserInfo;
  6410. }());
  6411. var FederatedAdditionalUserInfoWithUsername = /** @class */ (function (_super) {
  6412. tslib.__extends(FederatedAdditionalUserInfoWithUsername, _super);
  6413. function FederatedAdditionalUserInfoWithUsername(isNewUser, providerId, profile, username) {
  6414. var _this = _super.call(this, isNewUser, providerId, profile) || this;
  6415. _this.username = username;
  6416. return _this;
  6417. }
  6418. return FederatedAdditionalUserInfoWithUsername;
  6419. }(GenericAdditionalUserInfo));
  6420. var FacebookAdditionalUserInfo = /** @class */ (function (_super) {
  6421. tslib.__extends(FacebookAdditionalUserInfo, _super);
  6422. function FacebookAdditionalUserInfo(isNewUser, profile) {
  6423. return _super.call(this, isNewUser, "facebook.com" /* ProviderId.FACEBOOK */, profile) || this;
  6424. }
  6425. return FacebookAdditionalUserInfo;
  6426. }(GenericAdditionalUserInfo));
  6427. var GithubAdditionalUserInfo = /** @class */ (function (_super) {
  6428. tslib.__extends(GithubAdditionalUserInfo, _super);
  6429. function GithubAdditionalUserInfo(isNewUser, profile) {
  6430. return _super.call(this, isNewUser, "github.com" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null) || this;
  6431. }
  6432. return GithubAdditionalUserInfo;
  6433. }(FederatedAdditionalUserInfoWithUsername));
  6434. var GoogleAdditionalUserInfo = /** @class */ (function (_super) {
  6435. tslib.__extends(GoogleAdditionalUserInfo, _super);
  6436. function GoogleAdditionalUserInfo(isNewUser, profile) {
  6437. return _super.call(this, isNewUser, "google.com" /* ProviderId.GOOGLE */, profile) || this;
  6438. }
  6439. return GoogleAdditionalUserInfo;
  6440. }(GenericAdditionalUserInfo));
  6441. var TwitterAdditionalUserInfo = /** @class */ (function (_super) {
  6442. tslib.__extends(TwitterAdditionalUserInfo, _super);
  6443. function TwitterAdditionalUserInfo(isNewUser, profile, screenName) {
  6444. return _super.call(this, isNewUser, "twitter.com" /* ProviderId.TWITTER */, profile, screenName) || this;
  6445. }
  6446. return TwitterAdditionalUserInfo;
  6447. }(FederatedAdditionalUserInfoWithUsername));
  6448. /**
  6449. * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
  6450. *
  6451. * @param userCredential - The user credential.
  6452. *
  6453. * @public
  6454. */
  6455. function getAdditionalUserInfo(userCredential) {
  6456. var _a = userCredential, user = _a.user, _tokenResponse = _a._tokenResponse;
  6457. if (user.isAnonymous && !_tokenResponse) {
  6458. // Handle the special case where signInAnonymously() gets called twice.
  6459. // No network call is made so there's nothing to actually fill this in
  6460. return {
  6461. providerId: null,
  6462. isNewUser: false,
  6463. profile: null
  6464. };
  6465. }
  6466. return _fromIdTokenResponse(_tokenResponse);
  6467. }
  6468. /**
  6469. * @license
  6470. * Copyright 2020 Google LLC
  6471. *
  6472. * Licensed under the Apache License, Version 2.0 (the "License");
  6473. * you may not use this file except in compliance with the License.
  6474. * You may obtain a copy of the License at
  6475. *
  6476. * http://www.apache.org/licenses/LICENSE-2.0
  6477. *
  6478. * Unless required by applicable law or agreed to in writing, software
  6479. * distributed under the License is distributed on an "AS IS" BASIS,
  6480. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6481. * See the License for the specific language governing permissions and
  6482. * limitations under the License.
  6483. */
  6484. // Non-optional auth methods.
  6485. /**
  6486. * Changes the type of persistence on the {@link Auth} instance for the currently saved
  6487. * `Auth` session and applies this type of persistence for future sign-in requests, including
  6488. * sign-in with redirect requests.
  6489. *
  6490. * @remarks
  6491. * This makes it easy for a user signing in to specify whether their session should be
  6492. * remembered or not. It also makes it easier to never persist the `Auth` state for applications
  6493. * that are shared by other users or have sensitive data.
  6494. *
  6495. * @example
  6496. * ```javascript
  6497. * setPersistence(auth, browserSessionPersistence);
  6498. * ```
  6499. *
  6500. * @param auth - The {@link Auth} instance.
  6501. * @param persistence - The {@link Persistence} to use.
  6502. * @returns A `Promise` that resolves once the persistence change has completed
  6503. *
  6504. * @public
  6505. */
  6506. function setPersistence(auth, persistence) {
  6507. return util.getModularInstance(auth).setPersistence(persistence);
  6508. }
  6509. /**
  6510. * Adds an observer for changes to the signed-in user's ID token.
  6511. *
  6512. * @remarks
  6513. * This includes sign-in, sign-out, and token refresh events.
  6514. *
  6515. * @param auth - The {@link Auth} instance.
  6516. * @param nextOrObserver - callback triggered on change.
  6517. * @param error - Deprecated. This callback is never triggered. Errors
  6518. * on signing in/out can be caught in promises returned from
  6519. * sign-in/sign-out functions.
  6520. * @param completed - Deprecated. This callback is never triggered.
  6521. *
  6522. * @public
  6523. */
  6524. function onIdTokenChanged(auth, nextOrObserver, error, completed) {
  6525. return util.getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
  6526. }
  6527. /**
  6528. * Adds a blocking callback that runs before an auth state change
  6529. * sets a new user.
  6530. *
  6531. * @param auth - The {@link Auth} instance.
  6532. * @param callback - callback triggered before new user value is set.
  6533. * If this throws, it blocks the user from being set.
  6534. * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
  6535. * callback throws, allowing you to undo any side effects.
  6536. */
  6537. function beforeAuthStateChanged(auth, callback, onAbort) {
  6538. return util.getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
  6539. }
  6540. /**
  6541. * Adds an observer for changes to the user's sign-in state.
  6542. *
  6543. * @remarks
  6544. * To keep the old behavior, see {@link onIdTokenChanged}.
  6545. *
  6546. * @param auth - The {@link Auth} instance.
  6547. * @param nextOrObserver - callback triggered on change.
  6548. * @param error - Deprecated. This callback is never triggered. Errors
  6549. * on signing in/out can be caught in promises returned from
  6550. * sign-in/sign-out functions.
  6551. * @param completed - Deprecated. This callback is never triggered.
  6552. *
  6553. * @public
  6554. */
  6555. function onAuthStateChanged(auth, nextOrObserver, error, completed) {
  6556. return util.getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
  6557. }
  6558. /**
  6559. * Sets the current language to the default device/browser preference.
  6560. *
  6561. * @param auth - The {@link Auth} instance.
  6562. *
  6563. * @public
  6564. */
  6565. function useDeviceLanguage(auth) {
  6566. util.getModularInstance(auth).useDeviceLanguage();
  6567. }
  6568. /**
  6569. * Asynchronously sets the provided user as {@link Auth.currentUser} on the
  6570. * {@link Auth} instance.
  6571. *
  6572. * @remarks
  6573. * A new instance copy of the user provided will be made and set as currentUser.
  6574. *
  6575. * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
  6576. * like other sign in methods.
  6577. *
  6578. * The operation fails with an error if the user to be updated belongs to a different Firebase
  6579. * project.
  6580. *
  6581. * @param auth - The {@link Auth} instance.
  6582. * @param user - The new {@link User}.
  6583. *
  6584. * @public
  6585. */
  6586. function updateCurrentUser(auth, user) {
  6587. return util.getModularInstance(auth).updateCurrentUser(user);
  6588. }
  6589. /**
  6590. * Signs out the current user.
  6591. *
  6592. * @param auth - The {@link Auth} instance.
  6593. *
  6594. * @public
  6595. */
  6596. function signOut(auth) {
  6597. return util.getModularInstance(auth).signOut();
  6598. }
  6599. /**
  6600. * Deletes and signs out the user.
  6601. *
  6602. * @remarks
  6603. * Important: this is a security-sensitive operation that requires the user to have recently
  6604. * signed in. If this requirement isn't met, ask the user to authenticate again and then call
  6605. * {@link reauthenticateWithCredential}.
  6606. *
  6607. * @param user - The user.
  6608. *
  6609. * @public
  6610. */
  6611. function deleteUser(user) {
  6612. return tslib.__awaiter(this, void 0, void 0, function () {
  6613. return tslib.__generator(this, function (_a) {
  6614. return [2 /*return*/, util.getModularInstance(user).delete()];
  6615. });
  6616. });
  6617. }
  6618. var MultiFactorSessionImpl = /** @class */ (function () {
  6619. function MultiFactorSessionImpl(type, credential, auth) {
  6620. this.type = type;
  6621. this.credential = credential;
  6622. this.auth = auth;
  6623. }
  6624. MultiFactorSessionImpl._fromIdtoken = function (idToken, auth) {
  6625. return new MultiFactorSessionImpl("enroll" /* MultiFactorSessionType.ENROLL */, idToken, auth);
  6626. };
  6627. MultiFactorSessionImpl._fromMfaPendingCredential = function (mfaPendingCredential) {
  6628. return new MultiFactorSessionImpl("signin" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);
  6629. };
  6630. MultiFactorSessionImpl.prototype.toJSON = function () {
  6631. var _a;
  6632. var key = this.type === "enroll" /* MultiFactorSessionType.ENROLL */
  6633. ? 'idToken'
  6634. : 'pendingCredential';
  6635. return {
  6636. multiFactorSession: (_a = {},
  6637. _a[key] = this.credential,
  6638. _a)
  6639. };
  6640. };
  6641. MultiFactorSessionImpl.fromJSON = function (obj) {
  6642. var _a, _b;
  6643. if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
  6644. if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
  6645. return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
  6646. }
  6647. else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
  6648. return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
  6649. }
  6650. }
  6651. return null;
  6652. };
  6653. return MultiFactorSessionImpl;
  6654. }());
  6655. /**
  6656. * @license
  6657. * Copyright 2020 Google LLC
  6658. *
  6659. * Licensed under the Apache License, Version 2.0 (the "License");
  6660. * you may not use this file except in compliance with the License.
  6661. * You may obtain a copy of the License at
  6662. *
  6663. * http://www.apache.org/licenses/LICENSE-2.0
  6664. *
  6665. * Unless required by applicable law or agreed to in writing, software
  6666. * distributed under the License is distributed on an "AS IS" BASIS,
  6667. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6668. * See the License for the specific language governing permissions and
  6669. * limitations under the License.
  6670. */
  6671. var MultiFactorResolverImpl = /** @class */ (function () {
  6672. function MultiFactorResolverImpl(session, hints, signInResolver) {
  6673. this.session = session;
  6674. this.hints = hints;
  6675. this.signInResolver = signInResolver;
  6676. }
  6677. /** @internal */
  6678. MultiFactorResolverImpl._fromError = function (authExtern, error) {
  6679. var _this = this;
  6680. var auth = _castAuth(authExtern);
  6681. var serverResponse = error.customData._serverResponse;
  6682. var hints = (serverResponse.mfaInfo || []).map(function (enrollment) {
  6683. return MultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  6684. });
  6685. _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6686. var session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
  6687. return new MultiFactorResolverImpl(session, hints, function (assertion) { return tslib.__awaiter(_this, void 0, void 0, function () {
  6688. var mfaResponse, idTokenResponse, _a, userCredential;
  6689. return tslib.__generator(this, function (_b) {
  6690. switch (_b.label) {
  6691. case 0: return [4 /*yield*/, assertion._process(auth, session)];
  6692. case 1:
  6693. mfaResponse = _b.sent();
  6694. // Clear out the unneeded fields from the old login response
  6695. delete serverResponse.mfaInfo;
  6696. delete serverResponse.mfaPendingCredential;
  6697. idTokenResponse = tslib.__assign(tslib.__assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
  6698. _a = error.operationType;
  6699. switch (_a) {
  6700. case "signIn" /* OperationType.SIGN_IN */: return [3 /*break*/, 2];
  6701. case "reauthenticate" /* OperationType.REAUTHENTICATE */: return [3 /*break*/, 5];
  6702. }
  6703. return [3 /*break*/, 6];
  6704. case 2: return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse)];
  6705. case 3:
  6706. userCredential = _b.sent();
  6707. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  6708. case 4:
  6709. _b.sent();
  6710. return [2 /*return*/, userCredential];
  6711. case 5:
  6712. _assert(error.user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6713. return [2 /*return*/, UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse)];
  6714. case 6:
  6715. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6716. _b.label = 7;
  6717. case 7: return [2 /*return*/];
  6718. }
  6719. });
  6720. }); });
  6721. };
  6722. MultiFactorResolverImpl.prototype.resolveSignIn = function (assertionExtern) {
  6723. return tslib.__awaiter(this, void 0, void 0, function () {
  6724. var assertion;
  6725. return tslib.__generator(this, function (_a) {
  6726. assertion = assertionExtern;
  6727. return [2 /*return*/, this.signInResolver(assertion)];
  6728. });
  6729. });
  6730. };
  6731. return MultiFactorResolverImpl;
  6732. }());
  6733. /**
  6734. * Provides a {@link MultiFactorResolver} suitable for completion of a
  6735. * multi-factor flow.
  6736. *
  6737. * @param auth - The {@link Auth} instance.
  6738. * @param error - The {@link MultiFactorError} raised during a sign-in, or
  6739. * reauthentication operation.
  6740. *
  6741. * @public
  6742. */
  6743. function getMultiFactorResolver(auth, error) {
  6744. var _a;
  6745. var authModular = util.getModularInstance(auth);
  6746. var errorInternal = error;
  6747. _assert(error.customData.operationType, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6748. _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6749. return MultiFactorResolverImpl._fromError(authModular, errorInternal);
  6750. }
  6751. /**
  6752. * @license
  6753. * Copyright 2020 Google LLC
  6754. *
  6755. * Licensed under the Apache License, Version 2.0 (the "License");
  6756. * you may not use this file except in compliance with the License.
  6757. * You may obtain a copy of the License at
  6758. *
  6759. * http://www.apache.org/licenses/LICENSE-2.0
  6760. *
  6761. * Unless required by applicable law or agreed to in writing, software
  6762. * distributed under the License is distributed on an "AS IS" BASIS,
  6763. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6764. * See the License for the specific language governing permissions and
  6765. * limitations under the License.
  6766. */
  6767. function startEnrollPhoneMfa(auth, request) {
  6768. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:start" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  6769. }
  6770. function finalizeEnrollPhoneMfa(auth, request) {
  6771. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:finalize" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  6772. }
  6773. function withdrawMfa(auth, request) {
  6774. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:withdraw" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
  6775. }
  6776. var MultiFactorUserImpl = /** @class */ (function () {
  6777. function MultiFactorUserImpl(user) {
  6778. var _this = this;
  6779. this.user = user;
  6780. this.enrolledFactors = [];
  6781. user._onReload(function (userInfo) {
  6782. if (userInfo.mfaInfo) {
  6783. _this.enrolledFactors = userInfo.mfaInfo.map(function (enrollment) {
  6784. return MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment);
  6785. });
  6786. }
  6787. });
  6788. }
  6789. MultiFactorUserImpl._fromUser = function (user) {
  6790. return new MultiFactorUserImpl(user);
  6791. };
  6792. MultiFactorUserImpl.prototype.getSession = function () {
  6793. return tslib.__awaiter(this, void 0, void 0, function () {
  6794. var _a, _b;
  6795. return tslib.__generator(this, function (_c) {
  6796. switch (_c.label) {
  6797. case 0:
  6798. _b = (_a = MultiFactorSessionImpl)._fromIdtoken;
  6799. return [4 /*yield*/, this.user.getIdToken()];
  6800. case 1: return [2 /*return*/, _b.apply(_a, [_c.sent(), this.user.auth])];
  6801. }
  6802. });
  6803. });
  6804. };
  6805. MultiFactorUserImpl.prototype.enroll = function (assertionExtern, displayName) {
  6806. return tslib.__awaiter(this, void 0, void 0, function () {
  6807. var assertion, session, finalizeMfaResponse;
  6808. return tslib.__generator(this, function (_a) {
  6809. switch (_a.label) {
  6810. case 0:
  6811. assertion = assertionExtern;
  6812. return [4 /*yield*/, this.getSession()];
  6813. case 1:
  6814. session = (_a.sent());
  6815. return [4 /*yield*/, _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName))];
  6816. case 2:
  6817. finalizeMfaResponse = _a.sent();
  6818. // New tokens will be issued after enrollment of the new second factors.
  6819. // They need to be updated on the user.
  6820. return [4 /*yield*/, this.user._updateTokensIfNecessary(finalizeMfaResponse)];
  6821. case 3:
  6822. // New tokens will be issued after enrollment of the new second factors.
  6823. // They need to be updated on the user.
  6824. _a.sent();
  6825. // The user needs to be reloaded to get the new multi-factor information
  6826. // from server. USER_RELOADED event will be triggered and `enrolledFactors`
  6827. // will be updated.
  6828. return [2 /*return*/, this.user.reload()];
  6829. }
  6830. });
  6831. });
  6832. };
  6833. MultiFactorUserImpl.prototype.unenroll = function (infoOrUid) {
  6834. return tslib.__awaiter(this, void 0, void 0, function () {
  6835. var mfaEnrollmentId, idToken, idTokenResponse, e_1;
  6836. return tslib.__generator(this, function (_a) {
  6837. switch (_a.label) {
  6838. case 0:
  6839. mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
  6840. return [4 /*yield*/, this.user.getIdToken()];
  6841. case 1:
  6842. idToken = _a.sent();
  6843. return [4 /*yield*/, _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
  6844. idToken: idToken,
  6845. mfaEnrollmentId: mfaEnrollmentId
  6846. }))];
  6847. case 2:
  6848. idTokenResponse = _a.sent();
  6849. // Remove the second factor from the user's list.
  6850. this.enrolledFactors = this.enrolledFactors.filter(function (_a) {
  6851. var uid = _a.uid;
  6852. return uid !== mfaEnrollmentId;
  6853. });
  6854. // Depending on whether the backend decided to revoke the user's session,
  6855. // the tokenResponse may be empty. If the tokens were not updated (and they
  6856. // are now invalid), reloading the user will discover this and invalidate
  6857. // the user's state accordingly.
  6858. return [4 /*yield*/, this.user._updateTokensIfNecessary(idTokenResponse)];
  6859. case 3:
  6860. // Depending on whether the backend decided to revoke the user's session,
  6861. // the tokenResponse may be empty. If the tokens were not updated (and they
  6862. // are now invalid), reloading the user will discover this and invalidate
  6863. // the user's state accordingly.
  6864. _a.sent();
  6865. _a.label = 4;
  6866. case 4:
  6867. _a.trys.push([4, 6, , 7]);
  6868. return [4 /*yield*/, this.user.reload()];
  6869. case 5:
  6870. _a.sent();
  6871. return [3 /*break*/, 7];
  6872. case 6:
  6873. e_1 = _a.sent();
  6874. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) !== "auth/".concat("user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */)) {
  6875. throw e_1;
  6876. }
  6877. return [3 /*break*/, 7];
  6878. case 7: return [2 /*return*/];
  6879. }
  6880. });
  6881. });
  6882. };
  6883. return MultiFactorUserImpl;
  6884. }());
  6885. var multiFactorUserCache = new WeakMap();
  6886. /**
  6887. * The {@link MultiFactorUser} corresponding to the user.
  6888. *
  6889. * @remarks
  6890. * This is used to access all multi-factor properties and operations related to the user.
  6891. *
  6892. * @param user - The user.
  6893. *
  6894. * @public
  6895. */
  6896. function multiFactor(user) {
  6897. var userModular = util.getModularInstance(user);
  6898. if (!multiFactorUserCache.has(userModular)) {
  6899. multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  6900. }
  6901. return multiFactorUserCache.get(userModular);
  6902. }
  6903. var name = "@firebase/auth";
  6904. var version = "0.21.1";
  6905. /**
  6906. * @license
  6907. * Copyright 2020 Google LLC
  6908. *
  6909. * Licensed under the Apache License, Version 2.0 (the "License");
  6910. * you may not use this file except in compliance with the License.
  6911. * You may obtain a copy of the License at
  6912. *
  6913. * http://www.apache.org/licenses/LICENSE-2.0
  6914. *
  6915. * Unless required by applicable law or agreed to in writing, software
  6916. * distributed under the License is distributed on an "AS IS" BASIS,
  6917. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6918. * See the License for the specific language governing permissions and
  6919. * limitations under the License.
  6920. */
  6921. var AuthInterop = /** @class */ (function () {
  6922. function AuthInterop(auth) {
  6923. this.auth = auth;
  6924. this.internalListeners = new Map();
  6925. }
  6926. AuthInterop.prototype.getUid = function () {
  6927. var _a;
  6928. this.assertAuthConfigured();
  6929. return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
  6930. };
  6931. AuthInterop.prototype.getToken = function (forceRefresh) {
  6932. return tslib.__awaiter(this, void 0, void 0, function () {
  6933. var accessToken;
  6934. return tslib.__generator(this, function (_a) {
  6935. switch (_a.label) {
  6936. case 0:
  6937. this.assertAuthConfigured();
  6938. return [4 /*yield*/, this.auth._initializationPromise];
  6939. case 1:
  6940. _a.sent();
  6941. if (!this.auth.currentUser) {
  6942. return [2 /*return*/, null];
  6943. }
  6944. return [4 /*yield*/, this.auth.currentUser.getIdToken(forceRefresh)];
  6945. case 2:
  6946. accessToken = _a.sent();
  6947. return [2 /*return*/, { accessToken: accessToken }];
  6948. }
  6949. });
  6950. });
  6951. };
  6952. AuthInterop.prototype.addAuthTokenListener = function (listener) {
  6953. this.assertAuthConfigured();
  6954. if (this.internalListeners.has(listener)) {
  6955. return;
  6956. }
  6957. var unsubscribe = this.auth.onIdTokenChanged(function (user) {
  6958. listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
  6959. });
  6960. this.internalListeners.set(listener, unsubscribe);
  6961. this.updateProactiveRefresh();
  6962. };
  6963. AuthInterop.prototype.removeAuthTokenListener = function (listener) {
  6964. this.assertAuthConfigured();
  6965. var unsubscribe = this.internalListeners.get(listener);
  6966. if (!unsubscribe) {
  6967. return;
  6968. }
  6969. this.internalListeners.delete(listener);
  6970. unsubscribe();
  6971. this.updateProactiveRefresh();
  6972. };
  6973. AuthInterop.prototype.assertAuthConfigured = function () {
  6974. _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);
  6975. };
  6976. AuthInterop.prototype.updateProactiveRefresh = function () {
  6977. if (this.internalListeners.size > 0) {
  6978. this.auth._startProactiveRefresh();
  6979. }
  6980. else {
  6981. this.auth._stopProactiveRefresh();
  6982. }
  6983. };
  6984. return AuthInterop;
  6985. }());
  6986. /**
  6987. * @license
  6988. * Copyright 2020 Google LLC
  6989. *
  6990. * Licensed under the Apache License, Version 2.0 (the "License");
  6991. * you may not use this file except in compliance with the License.
  6992. * You may obtain a copy of the License at
  6993. *
  6994. * http://www.apache.org/licenses/LICENSE-2.0
  6995. *
  6996. * Unless required by applicable law or agreed to in writing, software
  6997. * distributed under the License is distributed on an "AS IS" BASIS,
  6998. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6999. * See the License for the specific language governing permissions and
  7000. * limitations under the License.
  7001. */
  7002. function getVersionForPlatform(clientPlatform) {
  7003. switch (clientPlatform) {
  7004. case "Node" /* ClientPlatform.NODE */:
  7005. return 'node';
  7006. case "ReactNative" /* ClientPlatform.REACT_NATIVE */:
  7007. return 'rn';
  7008. case "Worker" /* ClientPlatform.WORKER */:
  7009. return 'webworker';
  7010. case "Cordova" /* ClientPlatform.CORDOVA */:
  7011. return 'cordova';
  7012. default:
  7013. return undefined;
  7014. }
  7015. }
  7016. /** @internal */
  7017. function registerAuth(clientPlatform) {
  7018. app._registerComponent(new component.Component("auth" /* _ComponentName.AUTH */, function (container, _a) {
  7019. var deps = _a.options;
  7020. var app = container.getProvider('app').getImmediate();
  7021. var heartbeatServiceProvider = container.getProvider('heartbeat');
  7022. var _b = app.options, apiKey = _b.apiKey, authDomain = _b.authDomain;
  7023. return (function (app, heartbeatServiceProvider) {
  7024. _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });
  7025. // Auth domain is optional if IdP sign in isn't being used
  7026. _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, {
  7027. appName: app.name
  7028. });
  7029. var config = {
  7030. apiKey: apiKey,
  7031. authDomain: authDomain,
  7032. clientPlatform: clientPlatform,
  7033. apiHost: "identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */,
  7034. tokenApiHost: "securetoken.googleapis.com" /* DefaultConfig.TOKEN_API_HOST */,
  7035. apiScheme: "https" /* DefaultConfig.API_SCHEME */,
  7036. sdkClientVersion: _getClientVersion(clientPlatform)
  7037. };
  7038. var authInstance = new AuthImpl(app, heartbeatServiceProvider, config);
  7039. _initializeAuthInstance(authInstance, deps);
  7040. return authInstance;
  7041. })(app, heartbeatServiceProvider);
  7042. }, "PUBLIC" /* ComponentType.PUBLIC */)
  7043. /**
  7044. * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
  7045. * For why we do this, See go/firebase-next-auth-init
  7046. */
  7047. .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
  7048. /**
  7049. * Because all firebase products that depend on auth depend on auth-internal directly,
  7050. * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
  7051. */
  7052. .setInstanceCreatedCallback(function (container, _instanceIdentifier, _instance) {
  7053. var authInternalProvider = container.getProvider("auth-internal" /* _ComponentName.AUTH_INTERNAL */);
  7054. authInternalProvider.initialize();
  7055. }));
  7056. app._registerComponent(new component.Component("auth-internal" /* _ComponentName.AUTH_INTERNAL */, function (container) {
  7057. var auth = _castAuth(container.getProvider("auth" /* _ComponentName.AUTH */).getImmediate());
  7058. return (function (auth) { return new AuthInterop(auth); })(auth);
  7059. }, "PRIVATE" /* ComponentType.PRIVATE */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
  7060. app.registerVersion(name, version, getVersionForPlatform(clientPlatform));
  7061. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  7062. app.registerVersion(name, version, 'cjs5');
  7063. }
  7064. var STORAGE_AVAILABLE_KEY = '__sak';
  7065. /**
  7066. * @license
  7067. * Copyright 2021 Google LLC
  7068. *
  7069. * Licensed under the Apache License, Version 2.0 (the "License");
  7070. * you may not use this file except in compliance with the License.
  7071. * You may obtain a copy of the License at
  7072. *
  7073. * http://www.apache.org/licenses/LICENSE-2.0
  7074. *
  7075. * Unless required by applicable law or agreed to in writing, software
  7076. * distributed under the License is distributed on an "AS IS" BASIS,
  7077. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7078. * See the License for the specific language governing permissions and
  7079. * limitations under the License.
  7080. */
  7081. /**
  7082. * An enum of factors that may be used for multifactor authentication.
  7083. *
  7084. * @public
  7085. */
  7086. var FactorId = {
  7087. /** Phone as second factor */
  7088. PHONE: 'phone'
  7089. };
  7090. /**
  7091. * Enumeration of supported providers.
  7092. *
  7093. * @public
  7094. */
  7095. var ProviderId = {
  7096. /** Facebook provider ID */
  7097. FACEBOOK: 'facebook.com',
  7098. /** GitHub provider ID */
  7099. GITHUB: 'github.com',
  7100. /** Google provider ID */
  7101. GOOGLE: 'google.com',
  7102. /** Password provider */
  7103. PASSWORD: 'password',
  7104. /** Phone provider */
  7105. PHONE: 'phone',
  7106. /** Twitter provider ID */
  7107. TWITTER: 'twitter.com'
  7108. };
  7109. /**
  7110. * Enumeration of supported sign-in methods.
  7111. *
  7112. * @public
  7113. */
  7114. var SignInMethod = {
  7115. /** Email link sign in method */
  7116. EMAIL_LINK: 'emailLink',
  7117. /** Email/password sign in method */
  7118. EMAIL_PASSWORD: 'password',
  7119. /** Facebook sign in method */
  7120. FACEBOOK: 'facebook.com',
  7121. /** GitHub sign in method */
  7122. GITHUB: 'github.com',
  7123. /** Google sign in method */
  7124. GOOGLE: 'google.com',
  7125. /** Phone sign in method */
  7126. PHONE: 'phone',
  7127. /** Twitter sign in method */
  7128. TWITTER: 'twitter.com'
  7129. };
  7130. /**
  7131. * Enumeration of supported operation types.
  7132. *
  7133. * @public
  7134. */
  7135. var OperationType = {
  7136. /** Operation involving linking an additional provider to an already signed-in user. */
  7137. LINK: 'link',
  7138. /** Operation involving using a provider to reauthenticate an already signed-in user. */
  7139. REAUTHENTICATE: 'reauthenticate',
  7140. /** Operation involving signing in a user. */
  7141. SIGN_IN: 'signIn'
  7142. };
  7143. /**
  7144. * An enumeration of the possible email action types.
  7145. *
  7146. * @public
  7147. */
  7148. var ActionCodeOperation = {
  7149. /** The email link sign-in action. */
  7150. EMAIL_SIGNIN: 'EMAIL_SIGNIN',
  7151. /** The password reset action. */
  7152. PASSWORD_RESET: 'PASSWORD_RESET',
  7153. /** The email revocation action. */
  7154. RECOVER_EMAIL: 'RECOVER_EMAIL',
  7155. /** The revert second factor addition email action. */
  7156. REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
  7157. /** The revert second factor addition email action. */
  7158. VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
  7159. /** The email verification action. */
  7160. VERIFY_EMAIL: 'VERIFY_EMAIL'
  7161. };
  7162. /**
  7163. * @license
  7164. * Copyright 2020 Google LLC
  7165. *
  7166. * Licensed under the Apache License, Version 2.0 (the "License");
  7167. * you may not use this file except in compliance with the License.
  7168. * You may obtain a copy of the License at
  7169. *
  7170. * http://www.apache.org/licenses/LICENSE-2.0
  7171. *
  7172. * Unless required by applicable law or agreed to in writing, software
  7173. * distributed under the License is distributed on an "AS IS" BASIS,
  7174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7175. * See the License for the specific language governing permissions and
  7176. * limitations under the License.
  7177. */
  7178. function startSignInPhoneMfa(auth, request) {
  7179. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:start" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  7180. }
  7181. function finalizeSignInPhoneMfa(auth, request) {
  7182. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  7183. }
  7184. /**
  7185. * @license
  7186. * Copyright 2020 Google LLC
  7187. *
  7188. * Licensed under the Apache License, Version 2.0 (the "License");
  7189. * you may not use this file except in compliance with the License.
  7190. * You may obtain a copy of the License at
  7191. *
  7192. * http://www.apache.org/licenses/LICENSE-2.0
  7193. *
  7194. * Unless required by applicable law or agreed to in writing, software
  7195. * distributed under the License is distributed on an "AS IS" BASIS,
  7196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7197. * See the License for the specific language governing permissions and
  7198. * limitations under the License.
  7199. */
  7200. function getRecaptchaParams(auth) {
  7201. return tslib.__awaiter(this, void 0, void 0, function () {
  7202. return tslib.__generator(this, function (_a) {
  7203. switch (_a.label) {
  7204. case 0: return [4 /*yield*/, _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/recaptchaParams" /* Endpoint.GET_RECAPTCHA_PARAM */)];
  7205. case 1: return [2 /*return*/, ((_a.sent()).recaptchaSiteKey || '')];
  7206. }
  7207. });
  7208. });
  7209. }
  7210. /**
  7211. * @license
  7212. * Copyright 2020 Google LLC
  7213. *
  7214. * Licensed under the Apache License, Version 2.0 (the "License");
  7215. * you may not use this file except in compliance with the License.
  7216. * You may obtain a copy of the License at
  7217. *
  7218. * http://www.apache.org/licenses/LICENSE-2.0
  7219. *
  7220. * Unless required by applicable law or agreed to in writing, software
  7221. * distributed under the License is distributed on an "AS IS" BASIS,
  7222. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7223. * See the License for the specific language governing permissions and
  7224. * limitations under the License.
  7225. */
  7226. /**
  7227. * Lazy accessor for window, since the compat layer won't tree shake this out,
  7228. * we need to make sure not to mess with window unless we have to
  7229. */
  7230. function _window() {
  7231. return window;
  7232. }
  7233. function _setWindowLocation(url) {
  7234. _window().location.href = url;
  7235. }
  7236. /**
  7237. * @license
  7238. * Copyright 2020 Google LLC.
  7239. *
  7240. * Licensed under the Apache License, Version 2.0 (the "License");
  7241. * you may not use this file except in compliance with the License.
  7242. * You may obtain a copy of the License at
  7243. *
  7244. * http://www.apache.org/licenses/LICENSE-2.0
  7245. *
  7246. * Unless required by applicable law or agreed to in writing, software
  7247. * distributed under the License is distributed on an "AS IS" BASIS,
  7248. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7249. * See the License for the specific language governing permissions and
  7250. * limitations under the License.
  7251. */
  7252. function _isWorker() {
  7253. return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
  7254. typeof _window()['importScripts'] === 'function');
  7255. }
  7256. function _getActiveServiceWorker() {
  7257. return tslib.__awaiter(this, void 0, void 0, function () {
  7258. var registration;
  7259. return tslib.__generator(this, function (_b) {
  7260. switch (_b.label) {
  7261. case 0:
  7262. if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
  7263. return [2 /*return*/, null];
  7264. }
  7265. _b.label = 1;
  7266. case 1:
  7267. _b.trys.push([1, 3, , 4]);
  7268. return [4 /*yield*/, navigator.serviceWorker.ready];
  7269. case 2:
  7270. registration = _b.sent();
  7271. return [2 /*return*/, registration.active];
  7272. case 3:
  7273. _b.sent();
  7274. return [2 /*return*/, null];
  7275. case 4: return [2 /*return*/];
  7276. }
  7277. });
  7278. });
  7279. }
  7280. function _getServiceWorkerController() {
  7281. var _a;
  7282. return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
  7283. }
  7284. function _getWorkerGlobalScope() {
  7285. return _isWorker() ? self : null;
  7286. }
  7287. /**
  7288. * @license
  7289. * Copyright 2020 Google LLC
  7290. *
  7291. * Licensed under the Apache License, Version 2.0 (the "License");
  7292. * you may not use this file except in compliance with the License.
  7293. * You may obtain a copy of the License at
  7294. *
  7295. * http://www.apache.org/licenses/LICENSE-2.0
  7296. *
  7297. * Unless required by applicable law or agreed to in writing, software
  7298. * distributed under the License is distributed on an "AS IS" BASIS,
  7299. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7300. * See the License for the specific language governing permissions and
  7301. * limitations under the License.
  7302. */
  7303. function getScriptParentElement() {
  7304. var _a, _b;
  7305. return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
  7306. }
  7307. function _loadJS(url) {
  7308. // TODO: consider adding timeout support & cancellation
  7309. return new Promise(function (resolve, reject) {
  7310. var el = document.createElement('script');
  7311. el.setAttribute('src', url);
  7312. el.onload = resolve;
  7313. el.onerror = function (e) {
  7314. var error = _createError("internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7315. error.customData = e;
  7316. reject(error);
  7317. };
  7318. el.type = 'text/javascript';
  7319. el.charset = 'UTF-8';
  7320. getScriptParentElement().appendChild(el);
  7321. });
  7322. }
  7323. function _generateCallbackName(prefix) {
  7324. return "__".concat(prefix).concat(Math.floor(Math.random() * 1000000));
  7325. }
  7326. /**
  7327. * @license
  7328. * Copyright 2020 Google LLC
  7329. *
  7330. * Licensed under the Apache License, Version 2.0 (the "License");
  7331. * you may not use this file except in compliance with the License.
  7332. * You may obtain a copy of the License at
  7333. *
  7334. * http://www.apache.org/licenses/LICENSE-2.0
  7335. *
  7336. * Unless required by applicable law or agreed to in writing, software
  7337. * distributed under the License is distributed on an "AS IS" BASIS,
  7338. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7339. * See the License for the specific language governing permissions and
  7340. * limitations under the License.
  7341. */
  7342. var _SOLVE_TIME_MS = 500;
  7343. var _EXPIRATION_TIME_MS = 60000;
  7344. var _WIDGET_ID_START = 1000000000000;
  7345. var MockReCaptcha = /** @class */ (function () {
  7346. function MockReCaptcha(auth) {
  7347. this.auth = auth;
  7348. this.counter = _WIDGET_ID_START;
  7349. this._widgets = new Map();
  7350. }
  7351. MockReCaptcha.prototype.render = function (container, parameters) {
  7352. var id = this.counter;
  7353. this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));
  7354. this.counter++;
  7355. return id;
  7356. };
  7357. MockReCaptcha.prototype.reset = function (optWidgetId) {
  7358. var _a;
  7359. var id = optWidgetId || _WIDGET_ID_START;
  7360. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());
  7361. this._widgets.delete(id);
  7362. };
  7363. MockReCaptcha.prototype.getResponse = function (optWidgetId) {
  7364. var _a;
  7365. var id = optWidgetId || _WIDGET_ID_START;
  7366. return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';
  7367. };
  7368. MockReCaptcha.prototype.execute = function (optWidgetId) {
  7369. var _a;
  7370. return tslib.__awaiter(this, void 0, void 0, function () {
  7371. var id;
  7372. return tslib.__generator(this, function (_b) {
  7373. id = optWidgetId || _WIDGET_ID_START;
  7374. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());
  7375. return [2 /*return*/, ''];
  7376. });
  7377. });
  7378. };
  7379. return MockReCaptcha;
  7380. }());
  7381. var MockWidget = /** @class */ (function () {
  7382. function MockWidget(containerOrId, appName, params) {
  7383. var _this = this;
  7384. this.params = params;
  7385. this.timerId = null;
  7386. this.deleted = false;
  7387. this.responseToken = null;
  7388. this.clickHandler = function () {
  7389. _this.execute();
  7390. };
  7391. var container = typeof containerOrId === 'string'
  7392. ? document.getElementById(containerOrId)
  7393. : containerOrId;
  7394. _assert(container, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, { appName: appName });
  7395. this.container = container;
  7396. this.isVisible = this.params.size !== 'invisible';
  7397. if (this.isVisible) {
  7398. this.execute();
  7399. }
  7400. else {
  7401. this.container.addEventListener('click', this.clickHandler);
  7402. }
  7403. }
  7404. MockWidget.prototype.getResponse = function () {
  7405. this.checkIfDeleted();
  7406. return this.responseToken;
  7407. };
  7408. MockWidget.prototype.delete = function () {
  7409. this.checkIfDeleted();
  7410. this.deleted = true;
  7411. if (this.timerId) {
  7412. clearTimeout(this.timerId);
  7413. this.timerId = null;
  7414. }
  7415. this.container.removeEventListener('click', this.clickHandler);
  7416. };
  7417. MockWidget.prototype.execute = function () {
  7418. var _this = this;
  7419. this.checkIfDeleted();
  7420. if (this.timerId) {
  7421. return;
  7422. }
  7423. this.timerId = window.setTimeout(function () {
  7424. _this.responseToken = generateRandomAlphaNumericString(50);
  7425. var _a = _this.params, callback = _a.callback, expiredCallback = _a["expired-callback"];
  7426. if (callback) {
  7427. try {
  7428. callback(_this.responseToken);
  7429. }
  7430. catch (e) { }
  7431. }
  7432. _this.timerId = window.setTimeout(function () {
  7433. _this.timerId = null;
  7434. _this.responseToken = null;
  7435. if (expiredCallback) {
  7436. try {
  7437. expiredCallback();
  7438. }
  7439. catch (e) { }
  7440. }
  7441. if (_this.isVisible) {
  7442. _this.execute();
  7443. }
  7444. }, _EXPIRATION_TIME_MS);
  7445. }, _SOLVE_TIME_MS);
  7446. };
  7447. MockWidget.prototype.checkIfDeleted = function () {
  7448. if (this.deleted) {
  7449. throw new Error('reCAPTCHA mock was already deleted!');
  7450. }
  7451. };
  7452. return MockWidget;
  7453. }());
  7454. function generateRandomAlphaNumericString(len) {
  7455. var chars = [];
  7456. var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7457. for (var i = 0; i < len; i++) {
  7458. chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
  7459. }
  7460. return chars.join('');
  7461. }
  7462. /**
  7463. * @license
  7464. * Copyright 2020 Google LLC
  7465. *
  7466. * Licensed under the Apache License, Version 2.0 (the "License");
  7467. * you may not use this file except in compliance with the License.
  7468. * You may obtain a copy of the License at
  7469. *
  7470. * http://www.apache.org/licenses/LICENSE-2.0
  7471. *
  7472. * Unless required by applicable law or agreed to in writing, software
  7473. * distributed under the License is distributed on an "AS IS" BASIS,
  7474. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7475. * See the License for the specific language governing permissions and
  7476. * limitations under the License.
  7477. */
  7478. // ReCaptcha will load using the same callback, so the callback function needs
  7479. // to be kept around
  7480. var _JSLOAD_CALLBACK = _generateCallbackName('rcb');
  7481. var NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);
  7482. var RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';
  7483. /**
  7484. * Loader for the GReCaptcha library. There should only ever be one of this.
  7485. */
  7486. var ReCaptchaLoaderImpl = /** @class */ (function () {
  7487. function ReCaptchaLoaderImpl() {
  7488. var _a;
  7489. this.hostLanguage = '';
  7490. this.counter = 0;
  7491. /**
  7492. * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise
  7493. * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but
  7494. * `window.grecaptcha.render()` will not. Another load will add it.
  7495. */
  7496. this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);
  7497. }
  7498. ReCaptchaLoaderImpl.prototype.load = function (auth, hl) {
  7499. var _this = this;
  7500. if (hl === void 0) { hl = ''; }
  7501. _assert(isHostLanguageValid(hl), auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7502. if (this.shouldResolveImmediately(hl)) {
  7503. return Promise.resolve(_window().grecaptcha);
  7504. }
  7505. return new Promise(function (resolve, reject) {
  7506. var networkTimeout = _window().setTimeout(function () {
  7507. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  7508. }, NETWORK_TIMEOUT_DELAY.get());
  7509. _window()[_JSLOAD_CALLBACK] = function () {
  7510. _window().clearTimeout(networkTimeout);
  7511. delete _window()[_JSLOAD_CALLBACK];
  7512. var recaptcha = _window().grecaptcha;
  7513. if (!recaptcha) {
  7514. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  7515. return;
  7516. }
  7517. // Wrap the greptcha render function so that we know if the developer has
  7518. // called it separately
  7519. var render = recaptcha.render;
  7520. recaptcha.render = function (container, params) {
  7521. var widgetId = render(container, params);
  7522. _this.counter++;
  7523. return widgetId;
  7524. };
  7525. _this.hostLanguage = hl;
  7526. resolve(recaptcha);
  7527. };
  7528. var url = "".concat(RECAPTCHA_BASE, "?").concat(util.querystring({
  7529. onload: _JSLOAD_CALLBACK,
  7530. render: 'explicit',
  7531. hl: hl
  7532. }));
  7533. _loadJS(url).catch(function () {
  7534. clearTimeout(networkTimeout);
  7535. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  7536. });
  7537. });
  7538. };
  7539. ReCaptchaLoaderImpl.prototype.clearedOneInstance = function () {
  7540. this.counter--;
  7541. };
  7542. ReCaptchaLoaderImpl.prototype.shouldResolveImmediately = function (hl) {
  7543. var _a;
  7544. // We can resolve immediately if:
  7545. // • grecaptcha is already defined AND (
  7546. // 1. the requested language codes are the same OR
  7547. // 2. there exists already a ReCaptcha on the page
  7548. // 3. the library was already loaded by the app
  7549. // In cases (2) and (3), we _can't_ reload as it would break the recaptchas
  7550. // that are already in the page
  7551. return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&
  7552. (hl === this.hostLanguage ||
  7553. this.counter > 0 ||
  7554. this.librarySeparatelyLoaded));
  7555. };
  7556. return ReCaptchaLoaderImpl;
  7557. }());
  7558. function isHostLanguageValid(hl) {
  7559. return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
  7560. }
  7561. var MockReCaptchaLoaderImpl = /** @class */ (function () {
  7562. function MockReCaptchaLoaderImpl() {
  7563. }
  7564. MockReCaptchaLoaderImpl.prototype.load = function (auth) {
  7565. return tslib.__awaiter(this, void 0, void 0, function () {
  7566. return tslib.__generator(this, function (_a) {
  7567. return [2 /*return*/, new MockReCaptcha(auth)];
  7568. });
  7569. });
  7570. };
  7571. MockReCaptchaLoaderImpl.prototype.clearedOneInstance = function () { };
  7572. return MockReCaptchaLoaderImpl;
  7573. }());
  7574. /**
  7575. * @license
  7576. * Copyright 2020 Google LLC
  7577. *
  7578. * Licensed under the Apache License, Version 2.0 (the "License");
  7579. * you may not use this file except in compliance with the License.
  7580. * You may obtain a copy of the License at
  7581. *
  7582. * http://www.apache.org/licenses/LICENSE-2.0
  7583. *
  7584. * Unless required by applicable law or agreed to in writing, software
  7585. * distributed under the License is distributed on an "AS IS" BASIS,
  7586. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7587. * See the License for the specific language governing permissions and
  7588. * limitations under the License.
  7589. */
  7590. var RECAPTCHA_VERIFIER_TYPE = 'recaptcha';
  7591. var DEFAULT_PARAMS = {
  7592. theme: 'light',
  7593. type: 'image'
  7594. };
  7595. /**
  7596. * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.
  7597. *
  7598. * @public
  7599. */
  7600. var RecaptchaVerifier = /** @class */ (function () {
  7601. /**
  7602. *
  7603. * @param containerOrId - The reCAPTCHA container parameter.
  7604. *
  7605. * @remarks
  7606. * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
  7607. * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
  7608. * an element ID. The corresponding element must also must be in the DOM at the time of
  7609. * initialization.
  7610. *
  7611. * @param parameters - The optional reCAPTCHA parameters.
  7612. *
  7613. * @remarks
  7614. * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
  7615. * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
  7616. * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
  7617. * 'invisible'.
  7618. *
  7619. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  7620. */
  7621. function RecaptchaVerifier(containerOrId, parameters, authExtern) {
  7622. if (parameters === void 0) { parameters = tslib.__assign({}, DEFAULT_PARAMS); }
  7623. this.parameters = parameters;
  7624. /**
  7625. * The application verifier type.
  7626. *
  7627. * @remarks
  7628. * For a reCAPTCHA verifier, this is 'recaptcha'.
  7629. */
  7630. this.type = RECAPTCHA_VERIFIER_TYPE;
  7631. this.destroyed = false;
  7632. this.widgetId = null;
  7633. this.tokenChangeListeners = new Set();
  7634. this.renderPromise = null;
  7635. this.recaptcha = null;
  7636. this.auth = _castAuth(authExtern);
  7637. this.isInvisible = this.parameters.size === 'invisible';
  7638. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  7639. var container = typeof containerOrId === 'string'
  7640. ? document.getElementById(containerOrId)
  7641. : containerOrId;
  7642. _assert(container, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7643. this.container = container;
  7644. this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
  7645. this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting
  7646. ? new MockReCaptchaLoaderImpl()
  7647. : new ReCaptchaLoaderImpl();
  7648. this.validateStartingState();
  7649. // TODO: Figure out if sdk version is needed
  7650. }
  7651. /**
  7652. * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
  7653. *
  7654. * @returns A Promise for the reCAPTCHA token.
  7655. */
  7656. RecaptchaVerifier.prototype.verify = function () {
  7657. return tslib.__awaiter(this, void 0, void 0, function () {
  7658. var id, recaptcha, response;
  7659. var _this = this;
  7660. return tslib.__generator(this, function (_a) {
  7661. switch (_a.label) {
  7662. case 0:
  7663. this.assertNotDestroyed();
  7664. return [4 /*yield*/, this.render()];
  7665. case 1:
  7666. id = _a.sent();
  7667. recaptcha = this.getAssertedRecaptcha();
  7668. response = recaptcha.getResponse(id);
  7669. if (response) {
  7670. return [2 /*return*/, response];
  7671. }
  7672. return [2 /*return*/, new Promise(function (resolve) {
  7673. var tokenChange = function (token) {
  7674. if (!token) {
  7675. return; // Ignore token expirations.
  7676. }
  7677. _this.tokenChangeListeners.delete(tokenChange);
  7678. resolve(token);
  7679. };
  7680. _this.tokenChangeListeners.add(tokenChange);
  7681. if (_this.isInvisible) {
  7682. recaptcha.execute(id);
  7683. }
  7684. })];
  7685. }
  7686. });
  7687. });
  7688. };
  7689. /**
  7690. * Renders the reCAPTCHA widget on the page.
  7691. *
  7692. * @returns A Promise that resolves with the reCAPTCHA widget ID.
  7693. */
  7694. RecaptchaVerifier.prototype.render = function () {
  7695. var _this = this;
  7696. try {
  7697. this.assertNotDestroyed();
  7698. }
  7699. catch (e) {
  7700. // This method returns a promise. Since it's not async (we want to return the
  7701. // _same_ promise if rendering is still occurring), the API surface should
  7702. // reject with the error rather than just throw
  7703. return Promise.reject(e);
  7704. }
  7705. if (this.renderPromise) {
  7706. return this.renderPromise;
  7707. }
  7708. this.renderPromise = this.makeRenderPromise().catch(function (e) {
  7709. _this.renderPromise = null;
  7710. throw e;
  7711. });
  7712. return this.renderPromise;
  7713. };
  7714. /** @internal */
  7715. RecaptchaVerifier.prototype._reset = function () {
  7716. this.assertNotDestroyed();
  7717. if (this.widgetId !== null) {
  7718. this.getAssertedRecaptcha().reset(this.widgetId);
  7719. }
  7720. };
  7721. /**
  7722. * Clears the reCAPTCHA widget from the page and destroys the instance.
  7723. */
  7724. RecaptchaVerifier.prototype.clear = function () {
  7725. var _this = this;
  7726. this.assertNotDestroyed();
  7727. this.destroyed = true;
  7728. this._recaptchaLoader.clearedOneInstance();
  7729. if (!this.isInvisible) {
  7730. this.container.childNodes.forEach(function (node) {
  7731. _this.container.removeChild(node);
  7732. });
  7733. }
  7734. };
  7735. RecaptchaVerifier.prototype.validateStartingState = function () {
  7736. _assert(!this.parameters.sitekey, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7737. _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7738. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  7739. };
  7740. RecaptchaVerifier.prototype.makeTokenCallback = function (existing) {
  7741. var _this = this;
  7742. return function (token) {
  7743. _this.tokenChangeListeners.forEach(function (listener) { return listener(token); });
  7744. if (typeof existing === 'function') {
  7745. existing(token);
  7746. }
  7747. else if (typeof existing === 'string') {
  7748. var globalFunc = _window()[existing];
  7749. if (typeof globalFunc === 'function') {
  7750. globalFunc(token);
  7751. }
  7752. }
  7753. };
  7754. };
  7755. RecaptchaVerifier.prototype.assertNotDestroyed = function () {
  7756. _assert(!this.destroyed, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7757. };
  7758. RecaptchaVerifier.prototype.makeRenderPromise = function () {
  7759. return tslib.__awaiter(this, void 0, void 0, function () {
  7760. var container, guaranteedEmpty;
  7761. return tslib.__generator(this, function (_a) {
  7762. switch (_a.label) {
  7763. case 0: return [4 /*yield*/, this.init()];
  7764. case 1:
  7765. _a.sent();
  7766. if (!this.widgetId) {
  7767. container = this.container;
  7768. if (!this.isInvisible) {
  7769. guaranteedEmpty = document.createElement('div');
  7770. container.appendChild(guaranteedEmpty);
  7771. container = guaranteedEmpty;
  7772. }
  7773. this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
  7774. }
  7775. return [2 /*return*/, this.widgetId];
  7776. }
  7777. });
  7778. });
  7779. };
  7780. RecaptchaVerifier.prototype.init = function () {
  7781. return tslib.__awaiter(this, void 0, void 0, function () {
  7782. var _a, siteKey;
  7783. return tslib.__generator(this, function (_b) {
  7784. switch (_b.label) {
  7785. case 0:
  7786. _assert(_isHttpOrHttps() && !_isWorker(), this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7787. return [4 /*yield*/, domReady()];
  7788. case 1:
  7789. _b.sent();
  7790. _a = this;
  7791. return [4 /*yield*/, this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined)];
  7792. case 2:
  7793. _a.recaptcha = _b.sent();
  7794. return [4 /*yield*/, getRecaptchaParams(this.auth)];
  7795. case 3:
  7796. siteKey = _b.sent();
  7797. _assert(siteKey, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7798. this.parameters.sitekey = siteKey;
  7799. return [2 /*return*/];
  7800. }
  7801. });
  7802. });
  7803. };
  7804. RecaptchaVerifier.prototype.getAssertedRecaptcha = function () {
  7805. _assert(this.recaptcha, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7806. return this.recaptcha;
  7807. };
  7808. return RecaptchaVerifier;
  7809. }());
  7810. function domReady() {
  7811. var resolver = null;
  7812. return new Promise(function (resolve) {
  7813. if (document.readyState === 'complete') {
  7814. resolve();
  7815. return;
  7816. }
  7817. // Document not ready, wait for load before resolving.
  7818. // Save resolver, so we can remove listener in case it was externally
  7819. // cancelled.
  7820. resolver = function () { return resolve(); };
  7821. window.addEventListener('load', resolver);
  7822. }).catch(function (e) {
  7823. if (resolver) {
  7824. window.removeEventListener('load', resolver);
  7825. }
  7826. throw e;
  7827. });
  7828. }
  7829. /**
  7830. * @license
  7831. * Copyright 2020 Google LLC
  7832. *
  7833. * Licensed under the Apache License, Version 2.0 (the "License");
  7834. * you may not use this file except in compliance with the License.
  7835. * You may obtain a copy of the License at
  7836. *
  7837. * http://www.apache.org/licenses/LICENSE-2.0
  7838. *
  7839. * Unless required by applicable law or agreed to in writing, software
  7840. * distributed under the License is distributed on an "AS IS" BASIS,
  7841. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7842. * See the License for the specific language governing permissions and
  7843. * limitations under the License.
  7844. */
  7845. var ConfirmationResultImpl = /** @class */ (function () {
  7846. function ConfirmationResultImpl(verificationId, onConfirmation) {
  7847. this.verificationId = verificationId;
  7848. this.onConfirmation = onConfirmation;
  7849. }
  7850. ConfirmationResultImpl.prototype.confirm = function (verificationCode) {
  7851. var authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
  7852. return this.onConfirmation(authCredential);
  7853. };
  7854. return ConfirmationResultImpl;
  7855. }());
  7856. /**
  7857. * Asynchronously signs in using a phone number.
  7858. *
  7859. * @remarks
  7860. * This method sends a code via SMS to the given
  7861. * phone number, and returns a {@link ConfirmationResult}. After the user
  7862. * provides the code sent to their phone, call {@link ConfirmationResult.confirm}
  7863. * with the code to sign the user in.
  7864. *
  7865. * For abuse prevention, this method also requires a {@link ApplicationVerifier}.
  7866. * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.
  7867. * This function can work on other platforms that do not support the
  7868. * {@link RecaptchaVerifier} (like React Native), but you need to use a
  7869. * third-party {@link ApplicationVerifier} implementation.
  7870. *
  7871. * @example
  7872. * ```javascript
  7873. * // 'recaptcha-container' is the ID of an element in the DOM.
  7874. * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
  7875. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  7876. * // Obtain a verificationCode from the user.
  7877. * const credential = await confirmationResult.confirm(verificationCode);
  7878. * ```
  7879. *
  7880. * @param auth - The {@link Auth} instance.
  7881. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7882. * @param appVerifier - The {@link ApplicationVerifier}.
  7883. *
  7884. * @public
  7885. */
  7886. function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {
  7887. return tslib.__awaiter(this, void 0, void 0, function () {
  7888. var authInternal, verificationId;
  7889. return tslib.__generator(this, function (_a) {
  7890. switch (_a.label) {
  7891. case 0:
  7892. authInternal = _castAuth(auth);
  7893. return [4 /*yield*/, _verifyPhoneNumber(authInternal, phoneNumber, util.getModularInstance(appVerifier))];
  7894. case 1:
  7895. verificationId = _a.sent();
  7896. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  7897. return signInWithCredential(authInternal, cred);
  7898. })];
  7899. }
  7900. });
  7901. });
  7902. }
  7903. /**
  7904. * Links the user account with the given phone number.
  7905. *
  7906. * @param user - The user.
  7907. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7908. * @param appVerifier - The {@link ApplicationVerifier}.
  7909. *
  7910. * @public
  7911. */
  7912. function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
  7913. return tslib.__awaiter(this, void 0, void 0, function () {
  7914. var userInternal, verificationId;
  7915. return tslib.__generator(this, function (_a) {
  7916. switch (_a.label) {
  7917. case 0:
  7918. userInternal = util.getModularInstance(user);
  7919. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, "phone" /* ProviderId.PHONE */)];
  7920. case 1:
  7921. _a.sent();
  7922. return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, util.getModularInstance(appVerifier))];
  7923. case 2:
  7924. verificationId = _a.sent();
  7925. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  7926. return linkWithCredential(userInternal, cred);
  7927. })];
  7928. }
  7929. });
  7930. });
  7931. }
  7932. /**
  7933. * Re-authenticates a user using a fresh phone credential.
  7934. *
  7935. * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.
  7936. *
  7937. * @param user - The user.
  7938. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7939. * @param appVerifier - The {@link ApplicationVerifier}.
  7940. *
  7941. * @public
  7942. */
  7943. function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
  7944. return tslib.__awaiter(this, void 0, void 0, function () {
  7945. var userInternal, verificationId;
  7946. return tslib.__generator(this, function (_a) {
  7947. switch (_a.label) {
  7948. case 0:
  7949. userInternal = util.getModularInstance(user);
  7950. return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, util.getModularInstance(appVerifier))];
  7951. case 1:
  7952. verificationId = _a.sent();
  7953. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  7954. return reauthenticateWithCredential(userInternal, cred);
  7955. })];
  7956. }
  7957. });
  7958. });
  7959. }
  7960. /**
  7961. * Returns a verification ID to be used in conjunction with the SMS code that is sent.
  7962. *
  7963. */
  7964. function _verifyPhoneNumber(auth, options, verifier) {
  7965. var _a;
  7966. return tslib.__awaiter(this, void 0, void 0, function () {
  7967. var recaptchaToken, phoneInfoOptions, session, response, mfaEnrollmentId, response, sessionInfo;
  7968. return tslib.__generator(this, function (_b) {
  7969. switch (_b.label) {
  7970. case 0: return [4 /*yield*/, verifier.verify()];
  7971. case 1:
  7972. recaptchaToken = _b.sent();
  7973. _b.label = 2;
  7974. case 2:
  7975. _b.trys.push([2, , 10, 11]);
  7976. _assert(typeof recaptchaToken === 'string', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7977. _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7978. phoneInfoOptions = void 0;
  7979. if (typeof options === 'string') {
  7980. phoneInfoOptions = {
  7981. phoneNumber: options
  7982. };
  7983. }
  7984. else {
  7985. phoneInfoOptions = options;
  7986. }
  7987. if (!('session' in phoneInfoOptions)) return [3 /*break*/, 7];
  7988. session = phoneInfoOptions.session;
  7989. if (!('phoneNumber' in phoneInfoOptions)) return [3 /*break*/, 4];
  7990. _assert(session.type === "enroll" /* MultiFactorSessionType.ENROLL */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7991. return [4 /*yield*/, startEnrollPhoneMfa(auth, {
  7992. idToken: session.credential,
  7993. phoneEnrollmentInfo: {
  7994. phoneNumber: phoneInfoOptions.phoneNumber,
  7995. recaptchaToken: recaptchaToken
  7996. }
  7997. })];
  7998. case 3:
  7999. response = _b.sent();
  8000. return [2 /*return*/, response.phoneSessionInfo.sessionInfo];
  8001. case 4:
  8002. _assert(session.type === "signin" /* MultiFactorSessionType.SIGN_IN */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8003. mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||
  8004. phoneInfoOptions.multiFactorUid;
  8005. _assert(mfaEnrollmentId, auth, "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */);
  8006. return [4 /*yield*/, startSignInPhoneMfa(auth, {
  8007. mfaPendingCredential: session.credential,
  8008. mfaEnrollmentId: mfaEnrollmentId,
  8009. phoneSignInInfo: {
  8010. recaptchaToken: recaptchaToken
  8011. }
  8012. })];
  8013. case 5:
  8014. response = _b.sent();
  8015. return [2 /*return*/, response.phoneResponseInfo.sessionInfo];
  8016. case 6: return [3 /*break*/, 9];
  8017. case 7: return [4 /*yield*/, sendPhoneVerificationCode(auth, {
  8018. phoneNumber: phoneInfoOptions.phoneNumber,
  8019. recaptchaToken: recaptchaToken
  8020. })];
  8021. case 8:
  8022. sessionInfo = (_b.sent()).sessionInfo;
  8023. return [2 /*return*/, sessionInfo];
  8024. case 9: return [3 /*break*/, 11];
  8025. case 10:
  8026. verifier._reset();
  8027. return [7 /*endfinally*/];
  8028. case 11: return [2 /*return*/];
  8029. }
  8030. });
  8031. });
  8032. }
  8033. /**
  8034. * Updates the user's phone number.
  8035. *
  8036. * @example
  8037. * ```
  8038. * // 'recaptcha-container' is the ID of an element in the DOM.
  8039. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  8040. * const provider = new PhoneAuthProvider(auth);
  8041. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  8042. * // Obtain the verificationCode from the user.
  8043. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  8044. * await updatePhoneNumber(user, phoneCredential);
  8045. * ```
  8046. *
  8047. * @param user - The user.
  8048. * @param credential - A credential authenticating the new phone number.
  8049. *
  8050. * @public
  8051. */
  8052. function updatePhoneNumber(user, credential) {
  8053. return tslib.__awaiter(this, void 0, void 0, function () {
  8054. return tslib.__generator(this, function (_a) {
  8055. switch (_a.label) {
  8056. case 0: return [4 /*yield*/, _link(util.getModularInstance(user), credential)];
  8057. case 1:
  8058. _a.sent();
  8059. return [2 /*return*/];
  8060. }
  8061. });
  8062. });
  8063. }
  8064. /**
  8065. * @license
  8066. * Copyright 2020 Google LLC
  8067. *
  8068. * Licensed under the Apache License, Version 2.0 (the "License");
  8069. * you may not use this file except in compliance with the License.
  8070. * You may obtain a copy of the License at
  8071. *
  8072. * http://www.apache.org/licenses/LICENSE-2.0
  8073. *
  8074. * Unless required by applicable law or agreed to in writing, software
  8075. * distributed under the License is distributed on an "AS IS" BASIS,
  8076. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8077. * See the License for the specific language governing permissions and
  8078. * limitations under the License.
  8079. */
  8080. /**
  8081. * Provider for generating an {@link PhoneAuthCredential}.
  8082. *
  8083. * @example
  8084. * ```javascript
  8085. * // 'recaptcha-container' is the ID of an element in the DOM.
  8086. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  8087. * const provider = new PhoneAuthProvider(auth);
  8088. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  8089. * // Obtain the verificationCode from the user.
  8090. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  8091. * const userCredential = await signInWithCredential(auth, phoneCredential);
  8092. * ```
  8093. *
  8094. * @public
  8095. */
  8096. var PhoneAuthProvider = /** @class */ (function () {
  8097. /**
  8098. * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
  8099. *
  8100. */
  8101. function PhoneAuthProvider(auth) {
  8102. /** Always set to {@link ProviderId}.PHONE. */
  8103. this.providerId = PhoneAuthProvider.PROVIDER_ID;
  8104. this.auth = _castAuth(auth);
  8105. }
  8106. /**
  8107. *
  8108. * Starts a phone number authentication flow by sending a verification code to the given phone
  8109. * number.
  8110. *
  8111. * @example
  8112. * ```javascript
  8113. * const provider = new PhoneAuthProvider(auth);
  8114. * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  8115. * // Obtain verificationCode from the user.
  8116. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  8117. * const userCredential = await signInWithCredential(auth, authCredential);
  8118. * ```
  8119. *
  8120. * @example
  8121. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  8122. * ```javascript
  8123. * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  8124. * // Obtain verificationCode from the user.
  8125. * const userCredential = confirmationResult.confirm(verificationCode);
  8126. * ```
  8127. *
  8128. * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
  8129. * E.164 format (e.g. +16505550101).
  8130. * @param applicationVerifier - For abuse prevention, this method also requires a
  8131. * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,
  8132. * {@link RecaptchaVerifier}.
  8133. *
  8134. * @returns A Promise for a verification ID that can be passed to
  8135. * {@link PhoneAuthProvider.credential} to identify this flow..
  8136. */
  8137. PhoneAuthProvider.prototype.verifyPhoneNumber = function (phoneOptions, applicationVerifier) {
  8138. return _verifyPhoneNumber(this.auth, phoneOptions, util.getModularInstance(applicationVerifier));
  8139. };
  8140. /**
  8141. * Creates a phone auth credential, given the verification ID from
  8142. * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
  8143. * mobile device.
  8144. *
  8145. * @example
  8146. * ```javascript
  8147. * const provider = new PhoneAuthProvider(auth);
  8148. * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  8149. * // Obtain verificationCode from the user.
  8150. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  8151. * const userCredential = signInWithCredential(auth, authCredential);
  8152. * ```
  8153. *
  8154. * @example
  8155. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  8156. * ```javascript
  8157. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  8158. * // Obtain verificationCode from the user.
  8159. * const userCredential = await confirmationResult.confirm(verificationCode);
  8160. * ```
  8161. *
  8162. * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
  8163. * @param verificationCode - The verification code sent to the user's mobile device.
  8164. *
  8165. * @returns The auth provider credential.
  8166. */
  8167. PhoneAuthProvider.credential = function (verificationId, verificationCode) {
  8168. return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
  8169. };
  8170. /**
  8171. * Generates an {@link AuthCredential} from a {@link UserCredential}.
  8172. * @param userCredential - The user credential.
  8173. */
  8174. PhoneAuthProvider.credentialFromResult = function (userCredential) {
  8175. var credential = userCredential;
  8176. return PhoneAuthProvider.credentialFromTaggedObject(credential);
  8177. };
  8178. /**
  8179. * Returns an {@link AuthCredential} when passed an error.
  8180. *
  8181. * @remarks
  8182. *
  8183. * This method works for errors like
  8184. * `auth/account-exists-with-different-credentials`. This is useful for
  8185. * recovering when attempting to set a user's phone number but the number
  8186. * in question is already tied to another account. For example, the following
  8187. * code tries to update the current user's phone number, and if that
  8188. * fails, links the user with the account associated with that number:
  8189. *
  8190. * ```js
  8191. * const provider = new PhoneAuthProvider(auth);
  8192. * const verificationId = await provider.verifyPhoneNumber(number, verifier);
  8193. * try {
  8194. * const code = ''; // Prompt the user for the verification code
  8195. * await updatePhoneNumber(
  8196. * auth.currentUser,
  8197. * PhoneAuthProvider.credential(verificationId, code));
  8198. * } catch (e) {
  8199. * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {
  8200. * const cred = PhoneAuthProvider.credentialFromError(e);
  8201. * await linkWithCredential(auth.currentUser, cred);
  8202. * }
  8203. * }
  8204. *
  8205. * // At this point, auth.currentUser.phoneNumber === number.
  8206. * ```
  8207. *
  8208. * @param error - The error to generate a credential from.
  8209. */
  8210. PhoneAuthProvider.credentialFromError = function (error) {
  8211. return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));
  8212. };
  8213. PhoneAuthProvider.credentialFromTaggedObject = function (_a) {
  8214. var tokenResponse = _a._tokenResponse;
  8215. if (!tokenResponse) {
  8216. return null;
  8217. }
  8218. var _b = tokenResponse, phoneNumber = _b.phoneNumber, temporaryProof = _b.temporaryProof;
  8219. if (phoneNumber && temporaryProof) {
  8220. return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
  8221. }
  8222. return null;
  8223. };
  8224. /** Always set to {@link ProviderId}.PHONE. */
  8225. PhoneAuthProvider.PROVIDER_ID = "phone" /* ProviderId.PHONE */;
  8226. /** Always set to {@link SignInMethod}.PHONE. */
  8227. PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone" /* SignInMethod.PHONE */;
  8228. return PhoneAuthProvider;
  8229. }());
  8230. var MultiFactorAssertionImpl = /** @class */ (function () {
  8231. function MultiFactorAssertionImpl(factorId) {
  8232. this.factorId = factorId;
  8233. }
  8234. MultiFactorAssertionImpl.prototype._process = function (auth, session, displayName) {
  8235. switch (session.type) {
  8236. case "enroll" /* MultiFactorSessionType.ENROLL */:
  8237. return this._finalizeEnroll(auth, session.credential, displayName);
  8238. case "signin" /* MultiFactorSessionType.SIGN_IN */:
  8239. return this._finalizeSignIn(auth, session.credential);
  8240. default:
  8241. return debugFail('unexpected MultiFactorSessionType');
  8242. }
  8243. };
  8244. return MultiFactorAssertionImpl;
  8245. }());
  8246. /**
  8247. * {@inheritdoc PhoneMultiFactorAssertion}
  8248. *
  8249. * @public
  8250. */
  8251. var PhoneMultiFactorAssertionImpl = /** @class */ (function (_super) {
  8252. tslib.__extends(PhoneMultiFactorAssertionImpl, _super);
  8253. function PhoneMultiFactorAssertionImpl(credential) {
  8254. var _this = _super.call(this, "phone" /* FactorId.PHONE */) || this;
  8255. _this.credential = credential;
  8256. return _this;
  8257. }
  8258. /** @internal */
  8259. PhoneMultiFactorAssertionImpl._fromCredential = function (credential) {
  8260. return new PhoneMultiFactorAssertionImpl(credential);
  8261. };
  8262. /** @internal */
  8263. PhoneMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
  8264. return finalizeEnrollPhoneMfa(auth, {
  8265. idToken: idToken,
  8266. displayName: displayName,
  8267. phoneVerificationInfo: this.credential._makeVerificationRequest()
  8268. });
  8269. };
  8270. /** @internal */
  8271. PhoneMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
  8272. return finalizeSignInPhoneMfa(auth, {
  8273. mfaPendingCredential: mfaPendingCredential,
  8274. phoneVerificationInfo: this.credential._makeVerificationRequest()
  8275. });
  8276. };
  8277. return PhoneMultiFactorAssertionImpl;
  8278. }(MultiFactorAssertionImpl));
  8279. /**
  8280. * Provider for generating a {@link PhoneMultiFactorAssertion}.
  8281. *
  8282. * @public
  8283. */
  8284. var PhoneMultiFactorGenerator = /** @class */ (function () {
  8285. function PhoneMultiFactorGenerator() {
  8286. }
  8287. /**
  8288. * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
  8289. *
  8290. * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
  8291. * @returns A {@link PhoneMultiFactorAssertion} which can be used with
  8292. * {@link MultiFactorResolver.resolveSignIn}
  8293. */
  8294. PhoneMultiFactorGenerator.assertion = function (credential) {
  8295. return PhoneMultiFactorAssertionImpl._fromCredential(credential);
  8296. };
  8297. /**
  8298. * The identifier of the phone second factor: `phone`.
  8299. */
  8300. PhoneMultiFactorGenerator.FACTOR_ID = 'phone';
  8301. return PhoneMultiFactorGenerator;
  8302. }());
  8303. exports.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY;
  8304. exports.ActionCodeOperation = ActionCodeOperation;
  8305. exports.ActionCodeURL = ActionCodeURL;
  8306. exports.AuthCredential = AuthCredential;
  8307. exports.AuthImpl = AuthImpl;
  8308. exports.BaseOAuthProvider = BaseOAuthProvider;
  8309. exports.Delay = Delay;
  8310. exports.EmailAuthCredential = EmailAuthCredential;
  8311. exports.EmailAuthProvider = EmailAuthProvider;
  8312. exports.FacebookAuthProvider = FacebookAuthProvider;
  8313. exports.FactorId = FactorId;
  8314. exports.FederatedAuthProvider = FederatedAuthProvider;
  8315. exports.FetchProvider = FetchProvider;
  8316. exports.GithubAuthProvider = GithubAuthProvider;
  8317. exports.GoogleAuthProvider = GoogleAuthProvider;
  8318. exports.OAuthCredential = OAuthCredential;
  8319. exports.OAuthProvider = OAuthProvider;
  8320. exports.OperationType = OperationType;
  8321. exports.PhoneAuthCredential = PhoneAuthCredential;
  8322. exports.PhoneAuthProvider = PhoneAuthProvider;
  8323. exports.PhoneMultiFactorGenerator = PhoneMultiFactorGenerator;
  8324. exports.ProviderId = ProviderId;
  8325. exports.RecaptchaVerifier = RecaptchaVerifier;
  8326. exports.SAMLAuthCredential = SAMLAuthCredential;
  8327. exports.SAMLAuthProvider = SAMLAuthProvider;
  8328. exports.STORAGE_AVAILABLE_KEY = STORAGE_AVAILABLE_KEY;
  8329. exports.SignInMethod = SignInMethod;
  8330. exports.TwitterAuthProvider = TwitterAuthProvider;
  8331. exports.UserImpl = UserImpl;
  8332. exports._assert = _assert;
  8333. exports._assertInstanceOf = _assertInstanceOf;
  8334. exports._assertLinkedStatus = _assertLinkedStatus;
  8335. exports._castAuth = _castAuth;
  8336. exports._createError = _createError;
  8337. exports._emulatorUrl = _emulatorUrl;
  8338. exports._fail = _fail;
  8339. exports._generateCallbackName = _generateCallbackName;
  8340. exports._getActiveServiceWorker = _getActiveServiceWorker;
  8341. exports._getClientVersion = _getClientVersion;
  8342. exports._getCurrentUrl = _getCurrentUrl;
  8343. exports._getInstance = _getInstance;
  8344. exports._getServiceWorkerController = _getServiceWorkerController;
  8345. exports._getWorkerGlobalScope = _getWorkerGlobalScope;
  8346. exports._isAndroid = _isAndroid;
  8347. exports._isChromeIOS = _isChromeIOS;
  8348. exports._isFirefox = _isFirefox;
  8349. exports._isIE10 = _isIE10;
  8350. exports._isIOS = _isIOS;
  8351. exports._isIOS7Or8 = _isIOS7Or8;
  8352. exports._isIOSStandalone = _isIOSStandalone;
  8353. exports._isIframe = _isIframe;
  8354. exports._isMobileBrowser = _isMobileBrowser;
  8355. exports._isSafari = _isSafari;
  8356. exports._isWorker = _isWorker;
  8357. exports._link = _link;
  8358. exports._loadJS = _loadJS;
  8359. exports._performApiRequest = _performApiRequest;
  8360. exports._persistenceKeyName = _persistenceKeyName;
  8361. exports._reauthenticate = _reauthenticate;
  8362. exports._setWindowLocation = _setWindowLocation;
  8363. exports._signInWithCredential = _signInWithCredential;
  8364. exports._window = _window;
  8365. exports.applyActionCode = applyActionCode;
  8366. exports.beforeAuthStateChanged = beforeAuthStateChanged;
  8367. exports.checkActionCode = checkActionCode;
  8368. exports.confirmPasswordReset = confirmPasswordReset;
  8369. exports.connectAuthEmulator = connectAuthEmulator;
  8370. exports.createUserWithEmailAndPassword = createUserWithEmailAndPassword;
  8371. exports.debugAssert = debugAssert;
  8372. exports.debugErrorMap = debugErrorMap;
  8373. exports.deleteUser = deleteUser;
  8374. exports.fetchSignInMethodsForEmail = fetchSignInMethodsForEmail;
  8375. exports.getAdditionalUserInfo = getAdditionalUserInfo;
  8376. exports.getIdToken = getIdToken;
  8377. exports.getIdTokenResult = getIdTokenResult;
  8378. exports.getMultiFactorResolver = getMultiFactorResolver;
  8379. exports.inMemoryPersistence = inMemoryPersistence;
  8380. exports.initializeAuth = initializeAuth;
  8381. exports.isSignInWithEmailLink = isSignInWithEmailLink;
  8382. exports.linkWithCredential = linkWithCredential;
  8383. exports.linkWithPhoneNumber = linkWithPhoneNumber;
  8384. exports.multiFactor = multiFactor;
  8385. exports.onAuthStateChanged = onAuthStateChanged;
  8386. exports.onIdTokenChanged = onIdTokenChanged;
  8387. exports.parseActionCodeURL = parseActionCodeURL;
  8388. exports.prodErrorMap = prodErrorMap;
  8389. exports.reauthenticateWithCredential = reauthenticateWithCredential;
  8390. exports.reauthenticateWithPhoneNumber = reauthenticateWithPhoneNumber;
  8391. exports.registerAuth = registerAuth;
  8392. exports.reload = reload;
  8393. exports.sendEmailVerification = sendEmailVerification;
  8394. exports.sendPasswordResetEmail = sendPasswordResetEmail;
  8395. exports.sendSignInLinkToEmail = sendSignInLinkToEmail;
  8396. exports.setPersistence = setPersistence;
  8397. exports.signInAnonymously = signInAnonymously;
  8398. exports.signInWithCredential = signInWithCredential;
  8399. exports.signInWithCustomToken = signInWithCustomToken;
  8400. exports.signInWithEmailAndPassword = signInWithEmailAndPassword;
  8401. exports.signInWithEmailLink = signInWithEmailLink;
  8402. exports.signInWithIdp = signInWithIdp;
  8403. exports.signInWithPhoneNumber = signInWithPhoneNumber;
  8404. exports.signOut = signOut;
  8405. exports.unlink = unlink;
  8406. exports.updateCurrentUser = updateCurrentUser;
  8407. exports.updateEmail = updateEmail;
  8408. exports.updatePassword = updatePassword;
  8409. exports.updatePhoneNumber = updatePhoneNumber;
  8410. exports.updateProfile = updateProfile;
  8411. exports.useDeviceLanguage = useDeviceLanguage;
  8412. exports.verifyBeforeUpdateEmail = verifyBeforeUpdateEmail;
  8413. exports.verifyPasswordResetCode = verifyPasswordResetCode;
  8414. //# sourceMappingURL=phone-ec5655af.js.map