@firebase/auth
Version:
The Firebase Authenticaton component of the Firebase JS SDK.
1,395 lines (1,333 loc) • 123 kB
TypeScript
/**
* Firebase Authentication
*
* @packageDocumentation
*/
import { CompleteFn } from '@firebase/util';
import { ErrorFactory } from '@firebase/util';
import { ErrorFn } from '@firebase/util';
import { FirebaseApp } from '@firebase/app';
import { FirebaseError } from '@firebase/util';
import { NextFn } from '@firebase/util';
import { Observer } from '@firebase/util';
import { Unsubscribe } from '@firebase/util';
/**
* A response from {@link checkActionCode}.
*
* @public
*/
export declare interface ActionCodeInfo {
/**
* The data associated with the action code.
*
* @remarks
* For the {@link ActionCodeOperation}.PASSWORD_RESET, {@link ActionCodeOperation}.VERIFY_EMAIL, and
* {@link ActionCodeOperation}.RECOVER_EMAIL actions, this object contains an email field with the address
* the email was sent to.
*
* For the {@link ActionCodeOperation}.RECOVER_EMAIL action, which allows a user to undo an email address
* change, this object also contains a `previousEmail` field with the user account's current
* email address. After the action completes, the user's email address will revert to the value
* in the `email` field from the value in `previousEmail` field.
*
* For the {@link ActionCodeOperation}.VERIFY_AND_CHANGE_EMAIL action, which allows a user to verify the
* email before updating it, this object contains a `previousEmail` field with the user account's
* email address before updating. After the action completes, the user's email address will be
* updated to the value in the `email` field from the value in `previousEmail` field.
*
* For the {@link ActionCodeOperation}.REVERT_SECOND_FACTOR_ADDITION action, which allows a user to
* unenroll a newly added second factor, this object contains a `multiFactorInfo` field with
* the information about the second factor. For phone second factor, the `multiFactorInfo`
* is a {@link MultiFactorInfo} object, which contains the phone number.
*/
data: {
email?: string | null;
multiFactorInfo?: MultiFactorInfo | null;
previousEmail?: string | null;
};
/**
* The type of operation that generated the action code.
*/
operation: typeof ActionCodeOperation[keyof typeof ActionCodeOperation];
}
/**
* An enumeration of the possible email action types.
*
* @public
*/
export declare const ActionCodeOperation: {
/** The email link sign-in action. */
readonly EMAIL_SIGNIN: "EMAIL_SIGNIN";
/** The password reset action. */
readonly PASSWORD_RESET: "PASSWORD_RESET";
/** The email revocation action. */
readonly RECOVER_EMAIL: "RECOVER_EMAIL";
/** The revert second factor addition email action. */
readonly REVERT_SECOND_FACTOR_ADDITION: "REVERT_SECOND_FACTOR_ADDITION";
/** The revert second factor addition email action. */
readonly VERIFY_AND_CHANGE_EMAIL: "VERIFY_AND_CHANGE_EMAIL";
/** The email verification action. */
readonly VERIFY_EMAIL: "VERIFY_EMAIL";
};
/**
* An interface that defines the required continue/state URL with optional Android and iOS
* bundle identifiers.
*
* @public
*/
export declare interface ActionCodeSettings {
/**
* Sets the Android package name.
*
* @remarks
* This will try to open the link in an android app if it is
* installed. If `installApp` is passed, it specifies whether to install the Android app if the
* device supports it and the app is not already installed. If this field is provided without
* a `packageName`, an error is thrown explaining that the `packageName` must be provided in
* conjunction with this field. If `minimumVersion` is specified, and an older version of the
* app is installed, the user is taken to the Play Store to upgrade the app.
*/
android?: {
installApp?: boolean;
minimumVersion?: string;
packageName: string;
};
/**
* When set to true, the action code link will be be sent as a Universal Link or Android App
* Link and will be opened by the app if installed.
*
* @remarks
* In the false case, the code will be sent to the web widget first and then on continue will
* redirect to the app if installed.
*
* @defaultValue false
*/
handleCodeInApp?: boolean;
/**
* Sets the iOS bundle ID.
*
* @remarks
* This will try to open the link in an iOS app if it is installed.
*
* App installation is not supported for iOS.
*/
iOS?: {
bundleId: string;
};
/**
* Sets the link continue/state URL.
*
* @remarks
* This has different meanings in different contexts:
* - When the link is handled in the web action widgets, this is the deep link in the
* `continueUrl` query parameter.
* - When the link is handled in the app directly, this is the `continueUrl` query parameter in
* the deep link of the Dynamic Link.
*/
url: string;
/**
* When multiple custom dynamic link domains are defined for a project, specify which one to use
* when the link is to be opened via a specified mobile app (for example, `example.page.link`).
*
*
* @defaultValue The first domain is automatically selected.
*/
dynamicLinkDomain?: string;
}
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A utility class to parse email action URLs such as password reset, email verification,
* email link sign in, etc.
*
* @public
*/
export declare class ActionCodeURL {
/**
* The API key of the email action link.
*/
readonly apiKey: string;
/**
* The action code of the email action link.
*/
readonly code: string;
/**
* The continue URL of the email action link. Null if not provided.
*/
readonly continueUrl: string | null;
/**
* The language code of the email action link. Null if not provided.
*/
readonly languageCode: string | null;
/**
* The action performed by the email action link. It returns from one of the types from
* {@link ActionCodeInfo}
*/
readonly operation: string;
/**
* The tenant ID of the email action link. Null if the email action is from the parent project.
*/
readonly tenantId: string | null;
/* Excluded from this release type: __constructor */
/**
* Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
* otherwise returns null.
*
* @param link - The email action link string.
* @returns The {@link ActionCodeURL} object, or null if the link is invalid.
*
* @public
*/
static parseLink(link: string): ActionCodeURL | null;
}
/**
* A structure containing additional user information from a federated identity provider.
*
* @public
*/
export declare interface AdditionalUserInfo {
/**
* Whether the user is new (created via sign-up) or existing (authenticated using sign-in).
*/
readonly isNewUser: boolean;
/**
* Map containing IDP-specific user data.
*/
readonly profile: Record<string, unknown> | null;
/**
* Identifier for the provider used to authenticate this user.
*/
readonly providerId: string | null;
/**
* The username if the provider is GitHub or Twitter.
*/
readonly username?: string | null;
}
declare interface APIUserInfo {
localId?: string;
displayName?: string;
photoUrl?: string;
email?: string;
emailVerified?: boolean;
phoneNumber?: string;
lastLoginAt?: number;
createdAt?: number;
tenantId?: string;
passwordHash?: string;
providerUserInfo?: ProviderUserInfo[];
mfaInfo?: MfaEnrollment[];
}
/**
* A verifier for domain verification and abuse prevention.
*
* @remarks
* Currently, the only implementation is {@link RecaptchaVerifier}.
*
* @public
*/
export declare interface ApplicationVerifier {
/**
* Identifies the type of application verifier (e.g. "recaptcha").
*/
readonly type: string;
/**
* Executes the verification process.
*
* @returns A Promise for a token that can be used to assert the validity of a request.
*/
verify(): Promise<string>;
}
declare interface ApplicationVerifierInternal extends ApplicationVerifier {
/* Excluded from this release type: _reset */
}
/**
* Applies a verification code sent to the user by email or other out-of-band mechanism.
*
* @param auth - The {@link Auth} instance.
* @param oobCode - A verification code sent to the user.
*
* @public
*/
export declare function applyActionCode(auth: Auth, oobCode: string): Promise<void>;
declare type AppName = string;
/**
* Interface representing Firebase Auth service.
*
* @remarks
* See {@link https://firebase.google.com/docs/auth/ | Firebase Authentication} for a full guide
* on how to use the Firebase Auth service.
*
* @public
*/
export declare interface Auth {
/** The {@link @firebase/app#FirebaseApp} associated with the `Auth` service instance. */
readonly app: FirebaseApp;
/** The name of the app associated with the `Auth` service instance. */
readonly name: string;
/** The {@link Config} used to initialize this instance. */
readonly config: Config;
/**
* Changes the type of persistence on the `Auth` instance.
*
* @remarks
* This will affect the currently saved Auth session and applies this type of persistence for
* future sign-in requests, including sign-in with redirect requests.
*
* This makes it easy for a user signing in to specify whether their session should be
* remembered or not. It also makes it easier to never persist the Auth state for applications
* that are shared by other users or have sensitive data.
*
* @example
* ```javascript
* auth.setPersistence(browserSessionPersistence);
* ```
*
* @param persistence - The {@link Persistence} to use.
*/
setPersistence(persistence: Persistence): Promise<void>;
/**
* The {@link Auth} instance's language code.
*
* @remarks
* This is a readable/writable property. When set to null, the default Firebase Console language
* setting is applied. The language code will propagate to email action templates (password
* reset, email verification and email change revocation), SMS templates for phone authentication,
* reCAPTCHA verifier and OAuth popup/redirect operations provided the specified providers support
* localization with the language code specified.
*/
languageCode: string | null;
/**
* The {@link Auth} instance's tenant ID.
*
* @remarks
* This is a readable/writable property. When you set the tenant ID of an {@link Auth} instance, all
* future sign-in/sign-up operations will pass this tenant ID and sign in or sign up users to
* the specified tenant project. When set to null, users are signed in to the parent project.
*
* @example
* ```javascript
* // Set the tenant ID on Auth instance.
* auth.tenantId = 'TENANT_PROJECT_ID';
*
* // All future sign-in request now include tenant ID.
* const result = await signInWithEmailAndPassword(auth, email, password);
* // result.user.tenantId should be 'TENANT_PROJECT_ID'.
* ```
*
* @defaultValue null
*/
tenantId: string | null;
/**
* The {@link Auth} instance's settings.
*
* @remarks
* This is used to edit/read configuration related options such as app verification mode for
* phone authentication.
*/
readonly settings: AuthSettings;
/**
* Adds an observer for changes to the user's sign-in state.
*
* @remarks
* To keep the old behavior, see {@link Auth.onIdTokenChanged}.
*
* @param nextOrObserver - callback triggered on change.
* @param error - callback triggered on error.
* @param completed - callback triggered when observer is removed.
*/
onAuthStateChanged(nextOrObserver: NextOrObserver<User | null>, error?: ErrorFn, completed?: CompleteFn): Unsubscribe;
/**
* Adds a blocking callback that runs before an auth state change
* sets a new user.
*
* @param callback - callback triggered before new user value is set.
* If this throws, it blocks the user from being set.
* @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
* callback throws, allowing you to undo any side effects.
*/
beforeAuthStateChanged(callback: (user: User | null) => void | Promise<void>, onAbort?: () => void): Unsubscribe;
/**
* Adds an observer for changes to the signed-in user's ID token.
*
* @remarks
* This includes sign-in, sign-out, and token refresh events.
*
* @param nextOrObserver - callback triggered on change.
* @param error - callback triggered on error.
* @param completed - callback triggered when observer is removed.
*/
onIdTokenChanged(nextOrObserver: NextOrObserver<User | null>, error?: ErrorFn, completed?: CompleteFn): Unsubscribe;
/** The currently signed-in user (or null). */
readonly currentUser: User | null;
/** The current emulator configuration (or null). */
readonly emulatorConfig: EmulatorConfig | null;
/**
* Asynchronously sets the provided user as {@link Auth.currentUser} on the {@link Auth} instance.
*
* @remarks
* A new instance copy of the user provided will be made and set as currentUser.
*
* This will trigger {@link Auth.onAuthStateChanged} and {@link Auth.onIdTokenChanged} listeners
* like other sign in methods.
*
* The operation fails with an error if the user to be updated belongs to a different Firebase
* project.
*
* @param user - The new {@link User}.
*/
updateCurrentUser(user: User | null): Promise<void>;
/**
* Sets the current language to the default device/browser preference.
*/
useDeviceLanguage(): void;
/**
* Signs out the current user.
*/
signOut(): Promise<void>;
}
/**
* Interface that represents the credentials returned by an {@link AuthProvider}.
*
* @remarks
* Implementations specify the details about each auth provider's credential requirements.
*
* @public
*/
export declare class AuthCredential {
/**
* The authentication provider ID for the credential.
*
* @remarks
* For example, 'facebook.com', or 'google.com'.
*/
readonly providerId: string;
/**
* The authentication sign in method for the credential.
*
* @remarks
* For example, {@link SignInMethod}.EMAIL_PASSWORD, or
* {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
* identifier as returned in {@link fetchSignInMethodsForEmail}.
*/
readonly signInMethod: string;
/* Excluded from this release type: __constructor */
/**
* Returns a JSON-serializable representation of this object.
*
* @returns a JSON-serializable representation of this object.
*/
toJSON(): object;
/* Excluded from this release type: _getIdTokenResponse */
/* Excluded from this release type: _linkToIdToken */
/* Excluded from this release type: _getReauthenticationResolver */
}
/**
* Interface for an `Auth` error.
*
* @public
*/
export declare interface AuthError extends FirebaseError {
/** Details about the Firebase Auth error. */
readonly customData: {
/** The name of the Firebase App which triggered this error. */
readonly appName: string;
/** The email address of the user's account, used for sign-in and linking. */
readonly email?: string;
/** The phone number of the user's account, used for sign-in and linking. */
readonly phoneNumber?: string;
/**
* The tenant ID being used for sign-in and linking.
*
* @remarks
* If you use {@link signInWithRedirect} to sign in,
* you have to set the tenant ID on the {@link Auth} instance again as the tenant ID is not persisted
* after redirection.
*/
readonly tenantId?: string;
};
}
/* Excluded from this release type: AuthErrorCode */
/**
* A map of potential `Auth` error codes, for easier comparison with errors
* thrown by the SDK.
*
* @remarks
* Note that you can't tree-shake individual keys
* in the map, so by using the map you might substantially increase your
* bundle size.
*
* @public
*/
export declare const AuthErrorCodes: {
readonly ADMIN_ONLY_OPERATION: "auth/admin-restricted-operation";
readonly ARGUMENT_ERROR: "auth/argument-error";
readonly APP_NOT_AUTHORIZED: "auth/app-not-authorized";
readonly APP_NOT_INSTALLED: "auth/app-not-installed";
readonly CAPTCHA_CHECK_FAILED: "auth/captcha-check-failed";
readonly CODE_EXPIRED: "auth/code-expired";
readonly CORDOVA_NOT_READY: "auth/cordova-not-ready";
readonly CORS_UNSUPPORTED: "auth/cors-unsupported";
readonly CREDENTIAL_ALREADY_IN_USE: "auth/credential-already-in-use";
readonly CREDENTIAL_MISMATCH: "auth/custom-token-mismatch";
readonly CREDENTIAL_TOO_OLD_LOGIN_AGAIN: "auth/requires-recent-login";
readonly DEPENDENT_SDK_INIT_BEFORE_AUTH: "auth/dependent-sdk-initialized-before-auth";
readonly DYNAMIC_LINK_NOT_ACTIVATED: "auth/dynamic-link-not-activated";
readonly EMAIL_CHANGE_NEEDS_VERIFICATION: "auth/email-change-needs-verification";
readonly EMAIL_EXISTS: "auth/email-already-in-use";
readonly EMULATOR_CONFIG_FAILED: "auth/emulator-config-failed";
readonly EXPIRED_OOB_CODE: "auth/expired-action-code";
readonly EXPIRED_POPUP_REQUEST: "auth/cancelled-popup-request";
readonly INTERNAL_ERROR: "auth/internal-error";
readonly INVALID_API_KEY: "auth/invalid-api-key";
readonly INVALID_APP_CREDENTIAL: "auth/invalid-app-credential";
readonly INVALID_APP_ID: "auth/invalid-app-id";
readonly INVALID_AUTH: "auth/invalid-user-token";
readonly INVALID_AUTH_EVENT: "auth/invalid-auth-event";
readonly INVALID_CERT_HASH: "auth/invalid-cert-hash";
readonly INVALID_CODE: "auth/invalid-verification-code";
readonly INVALID_CONTINUE_URI: "auth/invalid-continue-uri";
readonly INVALID_CORDOVA_CONFIGURATION: "auth/invalid-cordova-configuration";
readonly INVALID_CUSTOM_TOKEN: "auth/invalid-custom-token";
readonly INVALID_DYNAMIC_LINK_DOMAIN: "auth/invalid-dynamic-link-domain";
readonly INVALID_EMAIL: "auth/invalid-email";
readonly INVALID_EMULATOR_SCHEME: "auth/invalid-emulator-scheme";
readonly INVALID_IDP_RESPONSE: "auth/invalid-credential";
readonly INVALID_MESSAGE_PAYLOAD: "auth/invalid-message-payload";
readonly INVALID_MFA_SESSION: "auth/invalid-multi-factor-session";
readonly INVALID_OAUTH_CLIENT_ID: "auth/invalid-oauth-client-id";
readonly INVALID_OAUTH_PROVIDER: "auth/invalid-oauth-provider";
readonly INVALID_OOB_CODE: "auth/invalid-action-code";
readonly INVALID_ORIGIN: "auth/unauthorized-domain";
readonly INVALID_PASSWORD: "auth/wrong-password";
readonly INVALID_PERSISTENCE: "auth/invalid-persistence-type";
readonly INVALID_PHONE_NUMBER: "auth/invalid-phone-number";
readonly INVALID_PROVIDER_ID: "auth/invalid-provider-id";
readonly INVALID_RECIPIENT_EMAIL: "auth/invalid-recipient-email";
readonly INVALID_SENDER: "auth/invalid-sender";
readonly INVALID_SESSION_INFO: "auth/invalid-verification-id";
readonly INVALID_TENANT_ID: "auth/invalid-tenant-id";
readonly MFA_INFO_NOT_FOUND: "auth/multi-factor-info-not-found";
readonly MFA_REQUIRED: "auth/multi-factor-auth-required";
readonly MISSING_ANDROID_PACKAGE_NAME: "auth/missing-android-pkg-name";
readonly MISSING_APP_CREDENTIAL: "auth/missing-app-credential";
readonly MISSING_AUTH_DOMAIN: "auth/auth-domain-config-required";
readonly MISSING_CODE: "auth/missing-verification-code";
readonly MISSING_CONTINUE_URI: "auth/missing-continue-uri";
readonly MISSING_IFRAME_START: "auth/missing-iframe-start";
readonly MISSING_IOS_BUNDLE_ID: "auth/missing-ios-bundle-id";
readonly MISSING_OR_INVALID_NONCE: "auth/missing-or-invalid-nonce";
readonly MISSING_MFA_INFO: "auth/missing-multi-factor-info";
readonly MISSING_MFA_SESSION: "auth/missing-multi-factor-session";
readonly MISSING_PHONE_NUMBER: "auth/missing-phone-number";
readonly MISSING_SESSION_INFO: "auth/missing-verification-id";
readonly MODULE_DESTROYED: "auth/app-deleted";
readonly NEED_CONFIRMATION: "auth/account-exists-with-different-credential";
readonly NETWORK_REQUEST_FAILED: "auth/network-request-failed";
readonly NULL_USER: "auth/null-user";
readonly NO_AUTH_EVENT: "auth/no-auth-event";
readonly NO_SUCH_PROVIDER: "auth/no-such-provider";
readonly OPERATION_NOT_ALLOWED: "auth/operation-not-allowed";
readonly OPERATION_NOT_SUPPORTED: "auth/operation-not-supported-in-this-environment";
readonly POPUP_BLOCKED: "auth/popup-blocked";
readonly POPUP_CLOSED_BY_USER: "auth/popup-closed-by-user";
readonly PROVIDER_ALREADY_LINKED: "auth/provider-already-linked";
readonly QUOTA_EXCEEDED: "auth/quota-exceeded";
readonly REDIRECT_CANCELLED_BY_USER: "auth/redirect-cancelled-by-user";
readonly REDIRECT_OPERATION_PENDING: "auth/redirect-operation-pending";
readonly REJECTED_CREDENTIAL: "auth/rejected-credential";
readonly SECOND_FACTOR_ALREADY_ENROLLED: "auth/second-factor-already-in-use";
readonly SECOND_FACTOR_LIMIT_EXCEEDED: "auth/maximum-second-factor-count-exceeded";
readonly TENANT_ID_MISMATCH: "auth/tenant-id-mismatch";
readonly TIMEOUT: "auth/timeout";
readonly TOKEN_EXPIRED: "auth/user-token-expired";
readonly TOO_MANY_ATTEMPTS_TRY_LATER: "auth/too-many-requests";
readonly UNAUTHORIZED_DOMAIN: "auth/unauthorized-continue-uri";
readonly UNSUPPORTED_FIRST_FACTOR: "auth/unsupported-first-factor";
readonly UNSUPPORTED_PERSISTENCE: "auth/unsupported-persistence-type";
readonly UNSUPPORTED_TENANT_OPERATION: "auth/unsupported-tenant-operation";
readonly UNVERIFIED_EMAIL: "auth/unverified-email";
readonly USER_CANCELLED: "auth/user-cancelled";
readonly USER_DELETED: "auth/user-not-found";
readonly USER_DISABLED: "auth/user-disabled";
readonly USER_MISMATCH: "auth/user-mismatch";
readonly USER_SIGNED_OUT: "auth/user-signed-out";
readonly WEAK_PASSWORD: "auth/weak-password";
readonly WEB_STORAGE_UNSUPPORTED: "auth/web-storage-unsupported";
readonly ALREADY_INITIALIZED: "auth/already-initialized";
};
/**
* A mapping of error codes to error messages.
*
* @remarks
*
* While error messages are useful for debugging (providing verbose textual
* context around what went wrong), these strings take up a lot of space in the
* compiled code. When deploying code in production, using {@link prodErrorMap}
* will save you roughly 10k compressed/gzipped over {@link debugErrorMap}. You
* can select the error map during initialization:
*
* ```javascript
* initializeAuth(app, {errorMap: debugErrorMap})
* ```
*
* When initializing Auth, {@link prodErrorMap} is default.
*
* @public
*/
export declare interface AuthErrorMap {
}
/* Excluded from this release type: AuthErrorParams */
/* Excluded from this release type: AuthEvent */
/* Excluded from this release type: AuthEventConsumer */
declare interface AuthEventError extends Error {
code: string;
message: string;
}
/* Excluded from this release type: AuthEventType */
/* Excluded from this release type: AuthInternal */
declare class AuthPopup {
readonly window: Window | null;
associatedEvent: string | null;
constructor(window: Window | null);
close(): void;
}
/**
* Interface that represents an auth provider, used to facilitate creating {@link AuthCredential}.
*
* @public
*/
export declare interface AuthProvider {
/**
* Provider for which credentials can be constructed.
*/
readonly providerId: string;
}
/**
* Interface representing an {@link Auth} instance's settings.
*
* @remarks Currently used for enabling/disabling app verification for phone Auth testing.
*
* @public
*/
export declare interface AuthSettings {
/**
* When set, this property disables app verification for the purpose of testing phone
* authentication. For this property to take effect, it needs to be set before rendering a
* reCAPTCHA app verifier. When this is disabled, a mock reCAPTCHA is rendered instead. This is
* useful for manual testing during development or for automated integration tests.
*
* In order to use this feature, you will need to
* {@link https://firebase.google.com/docs/auth/web/phone-auth#test-with-whitelisted-phone-numbers | whitelist your phone number}
* via the Firebase Console.
*
* The default value is false (app verification is enabled).
*/
appVerificationDisabledForTesting: boolean;
}
/**
* MFA Info as returned by the API
*/
declare interface BaseMfaEnrollment {
mfaEnrollmentId: string;
enrolledAt: number;
displayName?: string;
}
/**
* Common code to all OAuth providers. This is separate from the
* {@link OAuthProvider} so that child providers (like
* {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
* Instead, they rely on a static `credential` method.
*/
declare abstract class BaseOAuthProvider extends FederatedAuthProvider implements AuthProvider {
/* Excluded from this release type: scopes */
/**
* Add an OAuth scope to the credential.
*
* @param scope - Provider OAuth scope to add.
*/
addScope(scope: string): AuthProvider;
/**
* Retrieve the current list of OAuth scopes.
*/
getScopes(): string[];
}
/**
* Adds a blocking callback that runs before an auth state change
* sets a new user.
*
* @param auth - The {@link Auth} instance.
* @param callback - callback triggered before new user value is set.
* If this throws, it blocks the user from being set.
* @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
* callback throws, allowing you to undo any side effects.
*/
export declare function beforeAuthStateChanged(auth: Auth, callback: (user: User | null) => void | Promise<void>, onAbort?: () => void): Unsubscribe;
/**
* An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
* for the underlying storage.
*
* @public
*/
export declare const browserLocalPersistence: Persistence;
/**
* An implementation of {@link PopupRedirectResolver} suitable for browser
* based applications.
*
* @public
*/
export declare const browserPopupRedirectResolver: PopupRedirectResolver;
/**
* An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
* for the underlying storage.
*
* @public
*/
export declare const browserSessionPersistence: Persistence;
/**
* Checks a verification code sent to the user by email or other out-of-band mechanism.
*
* @returns metadata about the code.
*
* @param auth - The {@link Auth} instance.
* @param oobCode - A verification code sent to the user.
*
* @public
*/
export declare function checkActionCode(auth: Auth, oobCode: string): Promise<ActionCodeInfo>;
/* Excluded from this release type: ClientPlatform */
export { CompleteFn }
/**
* Interface representing the `Auth` config.
*
* @public
*/
export declare interface Config {
/**
* The API Key used to communicate with the Firebase Auth backend.
*/
apiKey: string;
/**
* The host at which the Firebase Auth backend is running.
*/
apiHost: string;
/**
* The scheme used to communicate with the Firebase Auth backend.
*/
apiScheme: string;
/**
* The host at which the Secure Token API is running.
*/
tokenApiHost: string;
/**
* The SDK Client Version.
*/
sdkClientVersion: string;
/**
* The domain at which the web widgets are hosted (provided via Firebase Config).
*/
authDomain?: string;
}
/* Excluded from this release type: ConfigInternal */
/**
* A result from a phone number sign-in, link, or reauthenticate call.
*
* @public
*/
export declare interface ConfirmationResult {
/**
* The phone number authentication operation's verification ID.
*
* @remarks
* This can be used along with the verification code to initialize a
* {@link PhoneAuthCredential}.
*/
readonly verificationId: string;
/**
* Finishes a phone number sign-in, link, or reauthentication.
*
* @example
* ```javascript
* const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
* // Obtain verificationCode from the user.
* const userCredential = await confirmationResult.confirm(verificationCode);
* ```
*
* @param verificationCode - The code that was sent to the user's mobile device.
*/
confirm(verificationCode: string): Promise<UserCredential>;
}
/**
* Completes the password reset process, given a confirmation code and new password.
*
* @param auth - The {@link Auth} instance.
* @param oobCode - A confirmation code sent to the user.
* @param newPassword - The new password.
*
* @public
*/
export declare function confirmPasswordReset(auth: Auth, oobCode: string, newPassword: string): Promise<void>;
/**
* Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
* Firebase Auth services.
*
* @remarks
* This must be called synchronously immediately following the first call to
* {@link initializeAuth}. Do not use with production credentials as emulator
* traffic is not encrypted.
*
*
* @example
* ```javascript
* connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
* ```
*
* @param auth - The {@link Auth} instance.
* @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
* @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
* `true` to disable the warning banner attached to the DOM.
*
* @public
*/
export declare function connectAuthEmulator(auth: Auth, url: string, options?: {
disableWarnings: boolean;
}): void;
/**
* Creates a new user account associated with the specified email address and password.
*
* @remarks
* On successful creation of the user account, this user will also be signed in to your application.
*
* User account creation can fail if the account already exists or the password is invalid.
*
* Note: The email address acts as a unique identifier for the user and enables an email-based
* password reset. This function will create a new user account and set the initial user password.
*
* @param auth - The {@link Auth} instance.
* @param email - The user's email address.
* @param password - The user's chosen password.
*
* @public
*/
export declare function createUserWithEmailAndPassword(auth: Auth, email: string, password: string): Promise<UserCredential>;
/**
* Map of OAuth Custom Parameters.
*
* @public
*/
export declare type CustomParameters = Record<string, string>;
/**
* A verbose error map with detailed descriptions for most error codes.
*
* See discussion at {@link AuthErrorMap}
*
* @public
*/
export declare const debugErrorMap: AuthErrorMap;
/**
* Deletes and signs out the user.
*
* @remarks
* Important: this is a security-sensitive operation that requires the user to have recently
* signed in. If this requirement isn't met, ask the user to authenticate again and then call
* {@link reauthenticateWithCredential}.
*
* @param user - The user.
*
* @public
*/
export declare function deleteUser(user: User): Promise<void>;
/**
* The dependencies that can be used to initialize an {@link Auth} instance.
*
* @remarks
*
* The modular SDK enables tree shaking by allowing explicit declarations of
* dependencies. For example, a web app does not need to include code that
* enables Cordova redirect sign in. That functionality is therefore split into
* {@link browserPopupRedirectResolver} and
* {@link cordovaPopupRedirectResolver}. The dependencies object is how Auth is
* configured to reduce bundle sizes.
*
* There are two ways to initialize an {@link Auth} instance: {@link getAuth} and
* {@link initializeAuth}. `getAuth` initializes everything using
* platform-specific configurations, while `initializeAuth` takes a
* `Dependencies` object directly, giving you more control over what is used.
*
* @public
*/
export declare interface Dependencies {
/**
* Which {@link Persistence} to use. If this is an array, the first
* `Persistence` that the device supports is used. The SDK searches for an
* existing account in order and, if one is found in a secondary
* `Persistence`, the account is moved to the primary `Persistence`.
*
* If no persistence is provided, the SDK falls back on
* {@link inMemoryPersistence}.
*/
persistence?: Persistence | Persistence[];
/**
* The {@link PopupRedirectResolver} to use. This value depends on the
* platform. Options are {@link browserPopupRedirectResolver} and
* {@link cordovaPopupRedirectResolver}. This field is optional if neither
* {@link signInWithPopup} or {@link signInWithRedirect} are being used.
*/
popupRedirectResolver?: PopupRedirectResolver;
/**
* Which {@link AuthErrorMap} to use.
*/
errorMap?: AuthErrorMap;
}
/**
* Interface that represents the credentials returned by {@link EmailAuthProvider} for
* {@link ProviderId}.PASSWORD
*
* @remarks
* Covers both {@link SignInMethod}.EMAIL_PASSWORD and
* {@link SignInMethod}.EMAIL_LINK.
*
* @public
*/
export declare class EmailAuthCredential extends AuthCredential {
/* Excluded from this release type: _email */
/* Excluded from this release type: _password */
/* Excluded from this release type: _tenantId */
/* Excluded from this release type: __constructor */
/* Excluded from this release type: _fromEmailAndPassword */
/* Excluded from this release type: _fromEmailAndCode */
/** {@inheritdoc AuthCredential.toJSON} */
toJSON(): object;
/**
* Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
*
* @param json - Either `object` or the stringified representation of the object. When string is
* provided, `JSON.parse` would be called first.
*
* @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
*/
static fromJSON(json: object | string): EmailAuthCredential | null;
/* Excluded from this release type: _getIdTokenResponse */
/* Excluded from this release type: _linkToIdToken */
/* Excluded from this release type: _getReauthenticationResolver */
}
/**
* Provider for generating {@link EmailAuthCredential}.
*
* @public
*/
export declare class EmailAuthProvider implements AuthProvider {
/**
* Always set to {@link ProviderId}.PASSWORD, even for email link.
*/
static readonly PROVIDER_ID: 'password';
/**
* Always set to {@link SignInMethod}.EMAIL_PASSWORD.
*/
static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password';
/**
* Always set to {@link SignInMethod}.EMAIL_LINK.
*/
static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink';
/**
* Always set to {@link ProviderId}.PASSWORD, even for email link.
*/
readonly providerId: "password";
/**
* Initialize an {@link AuthCredential} using an email and password.
*
* @example
* ```javascript
* const authCredential = EmailAuthProvider.credential(email, password);
* const userCredential = await signInWithCredential(auth, authCredential);
* ```
*
* @example
* ```javascript
* const userCredential = await signInWithEmailAndPassword(auth, email, password);
* ```
*
* @param email - Email address.
* @param password - User account password.
* @returns The auth provider credential.
*/
static credential(email: string, password: string): EmailAuthCredential;
/**
* Initialize an {@link AuthCredential} using an email and an email link after a sign in with
* email link operation.
*
* @example
* ```javascript
* const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
* const userCredential = await signInWithCredential(auth, authCredential);
* ```
*
* @example
* ```javascript
* await sendSignInLinkToEmail(auth, email);
* // Obtain emailLink from user.
* const userCredential = await signInWithEmailLink(auth, email, emailLink);
* ```
*
* @param auth - The {@link Auth} instance used to verify the link.
* @param email - Email address.
* @param emailLink - Sign-in email link.
* @returns - The auth provider credential.
*/
static credentialWithLink(email: string, emailLink: string): EmailAuthCredential;
}
/**
* Configuration of Firebase Authentication Emulator.
* @public
*/
export declare interface EmulatorConfig {
/**
* The protocol used to communicate with the emulator ("http"/"https").
*/
readonly protocol: string;
/**
* The hostname of the emulator, which may be a domain ("localhost"), IPv4 address ("127.0.0.1")
* or quoted IPv6 address ("[::1]").
*/
readonly host: string;
/**
* The port of the emulator, or null if port isn't specified (i.e. protocol default).
*/
readonly port: number | null;
/**
* The emulator-specific options.
*/
readonly options: {
/**
* Whether the warning banner attached to the DOM was disabled.
*/
readonly disableWarnings: boolean;
};
}
export { ErrorFn }
/* Excluded from this release type: EventManager */
/**
* Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
*
* @example
* ```javascript
* // Sign in using a redirect.
* const provider = new FacebookAuthProvider();
* // Start a sign in process for an unauthenticated user.
* provider.addScope('user_birthday');
* await signInWithRedirect(auth, provider);
* // This will trigger a full page redirect away from your app
*
* // After returning from the redirect when your app initializes you can obtain the result
* const result = await getRedirectResult(auth);
* if (result) {
* // This is the signed-in user
* const user = result.user;
* // This gives you a Facebook Access Token.
* const credential = FacebookAuthProvider.credentialFromResult(result);
* const token = credential.accessToken;
* }
* ```
*
* @example
* ```javascript
* // Sign in using a popup.
* const provider = new FacebookAuthProvider();
* provider.addScope('user_birthday');
* const result = await signInWithPopup(auth, provider);
*
* // The signed-in user info.
* const user = result.user;
* // This gives you a Facebook Access Token.
* const credential = FacebookAuthProvider.credentialFromResult(result);
* const token = credential.accessToken;
* ```
*
* @public
*/
export declare class FacebookAuthProvider extends BaseOAuthProvider {
/** Always set to {@link SignInMethod}.FACEBOOK. */
static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com';
/** Always set to {@link ProviderId}.FACEBOOK. */
static readonly PROVIDER_ID: 'facebook.com';
constructor();
/**
* Creates a credential for Facebook.
*
* @example
* ```javascript
* // `event` from the Facebook auth.authResponseChange callback.
* const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
* const result = await signInWithCredential(credential);
* ```
*
* @param accessToken - Facebook access token.
*/
static credential(accessToken: string): OAuthCredential;
/**
* Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
*
* @param userCredential - The user credential.
*/
static credentialFromResult(userCredential: UserCredential): OAuthCredential | null;
/**
* Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
* thrown during a sign-in, link, or reauthenticate operation.
*
* @param userCredential - The user credential.
*/
static credentialFromError(error: FirebaseError): OAuthCredential | null;
private static credentialFromTaggedObject;
}
/**
* An enum of factors that may be used for multifactor authentication.
*
* @public
*/
export declare const FactorId: {
/** Phone as second factor */
readonly PHONE: "phone";
};
/**
* The base class for all Federated providers (OAuth (including OIDC), SAML).
*
* This class is not meant to be instantiated directly.
*
* @public
*/
declare abstract class FederatedAuthProvider implements AuthProvider {
readonly providerId: string;
/* Excluded from this release type: defaultLanguageCode */
/* Excluded from this release type: customParameters */
/**
* Constructor for generic OAuth providers.
*
* @param providerId - Provider for which credentials should be generated.
*/
constructor(providerId: string);
/**
* Set the language gode.
*
* @param languageCode - language code
*/
setDefaultLanguage(languageCode: string | null): void;
/**
* Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
* operations.
*
* @remarks
* For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
* `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
*
* @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
*/
setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider;
/**
* Retrieve the current list of {@link CustomParameters}.
*/
getCustomParameters(): CustomParameters;
}
/**
* Gets the list of possible sign in methods for the given email address.
*
* @remarks
* This is useful to differentiate methods of sign-in for the same provider, eg.
* {@link EmailAuthProvider} which has 2 methods of sign-in,
* {@link SignInMethod}.EMAIL_PASSWORD and
* {@link SignInMethod}.EMAIL_LINK.
*
* @param auth - The {@link Auth} instance.
* @param email - The user's email address.
*
* @public
*/
export declare function fetchSignInMethodsForEmail(auth: Auth, email: string): Promise<string[]>;
declare interface FinalizeMfaResponse {
idToken: string;
refreshToken: string;
}
/* Excluded from this release type: GenericAuthErrorParams */
/**
* Extracts provider specific {@link AdditionalUserInfo} for the given credential.
*
* @param userCredential - The user credential.
*
* @public
*/
export declare function getAdditionalUserInfo(userCredential: UserCredential): AdditionalUserInfo | null;
/**
* Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
* If no instance exists, initializes an Auth instance with platform-specific default dependencies.
*
* @param app - The Firebase App.
*
* @public
*/
export declare function getAuth(app?: FirebaseApp): Auth;
/**
* Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
*
* @remarks
* Returns the current token if it has not expired or if it will not expire in the next five
* minutes. Otherwise, this will refresh the token and return a new one.
*
* @param user - The user.
* @param forceRefresh - Force refresh regardless of token expiration.
*
* @public
*/
export declare function getIdToken(user: User, forceRefresh?: boolean): Promise<string>;
/**
* Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.
*
* @remarks
* Returns the current token if it has not expired or if it will not expire in the next five
* minutes. Otherwise, this will refresh the token and return a new one.
*
* @param user - The user.
* @param forceRefresh - Force refresh regardless of token expiration.
*
* @public
*/
export declare function getIdTokenResult(user: User, forceRefresh?: boolean): Promise<IdTokenResult>;
/**
* Provides a {@link MultiFactorResolver} suitable for completion of a
* multi-factor flow.
*
* @param auth - The {@link Auth} instance.
* @param error - The {@link MultiFactorError} raised during a sign-in, or
* reauthentication operation.
*
* @public
*/
export declare function getMultiFactorResolver(auth: Auth, error: MultiFactorError): MultiFactorResolver;
/**
* Returns a {@link UserCredential} from the redirect-based sign-in flow.
*
* @remarks
* If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an
* error. If no redirect operation was called, returns a {@link UserCredential}
* with a null `user`.
*
* @example
* ```javascript
* // Sign in using a redirect.
* const provider = new FacebookAuthProvider();
* // You can add additional scopes to the provider:
* provider.addScope('user_birthday');
* // Start a sign in process for an unauthenticated user.
* await signInWithRedirect(auth, provider);
* // This will trigger a full page redirect away from your app
*
* // After returning from the redirect when your app initializes you can obtain the result
* const result = await getRedirectResult(auth);
* if (result) {
* // This is the signed-in user
* const user = result.user;
* // This gives you a Facebook Access Token.
* const credential = provider.credentialFromResult(auth, result);
* const token = credential.accessToken;
* }
* // As this API can be used for sign-in, linking and reauthentication,
* // check the operationType to determine what triggered this redirect
* // operation.
* const operationType = result.operationType;
* ```
*
* @param auth - The {@link Auth} instance.
* @param resolver - An instance of {@link PopupRedirectResolver}, optional
* if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
*
* @public
*/
export declare function getRedirectResult(auth: Auth, resolver?: PopupRedirectResolver): Promise<UserCredential | null>;
/**
* Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
*
* @remarks
* GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
* the {@link signInWithPopup} handler:
*
* @example
* ```javascript
* // Sign in using a redirect.
* const provider = new GithubAuthProvider();
* // Start a sign in process for an unauthenticated user.
* provider.addScope('repo');
* await signInWithRedirect(auth, provider);
* // This will trigger a full page redirect away from your app
*
* // After returning from the redirect when your app initializes you can obtain the result
* const result = await getRedirectResult(auth);
* if (result) {
* // This is the signed-in user
* const user = result.user;
* // This gives you a Github Access Token.
* const credential = GithubAuthProvider.credentialFromResult(result);
* const token = credential.accessToken;
* }
* ```
*
* @example
* ```javascript
* // Sign in using a popup.
* const provider = new GithubAuthProvider();
* provider.addScope('repo');
* const result = await signInWithPopup(auth, provider);
*
* // The signed-in user info.
* const user = result.user;
* // This gives you a Github Access Token.
* const credential = GithubAuthProvider.credentialFromResult(result);
* const token = credential.accessToken;
* ```
* @public
*/
export declare class GithubAuthProvider extends BaseOAuthProvider {
/** Always set to {@link SignInMethod}.GITHUB. */
static readonly GITHUB_SIGN_IN_METHOD: 'github.com';
/** Always set to {@link ProviderId}.GITHUB. */
static readonly PROVIDER_ID: 'github.com';
constructor();
/**
* Creates a credential for Github.
*
* @param accessToken - Github access token.
*/
static credential(accessToken: string): OAuthCredential;
/**
* Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
*
* @param userCredential - The user credential.
*/
static credentialFromResult(userCredential: UserCredential): OAuthCredential | null;
/**
* Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
* thrown during a sign-in, link, or reauthenticate operation.
*
* @param userCredential - The user credential.
*/
static credentialFromError(error: FirebaseError): OAuthCredential | null;
private static credentialFromTaggedObject;
}
/**
* Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
*
* @example
* ```javascript
* // Sign in using a redirect.
* const provider = new GoogleAuthProvider();
* // Start a sign in process for an unauthenticated u