diff --git a/etc/firebase-admin.auth.api.md b/etc/firebase-admin.auth.api.md index 7e10a8a3f1..820a30cda7 100644 --- a/etc/firebase-admin.auth.api.md +++ b/etc/firebase-admin.auth.api.md @@ -155,14 +155,13 @@ export interface AuthProviderConfigFilter { } // @public -export class BaseAuth { +export abstract class BaseAuth { createCustomToken(uid: string, developerClaims?: object): Promise; createProviderConfig(config: AuthProviderConfig): Promise; createSessionCookie(idToken: string, sessionCookieOptions: SessionCookieOptions): Promise; createUser(properties: CreateRequest): Promise; deleteProviderConfig(providerId: string): Promise; deleteUser(uid: string): Promise; - // (undocumented) deleteUsers(uids: string[]): Promise; generateEmailVerificationLink(email: string, actionCodeSettings?: ActionCodeSettings): Promise; generatePasswordResetLink(email: string, actionCodeSettings?: ActionCodeSettings): Promise; @@ -205,7 +204,6 @@ export type CreateTenantRequest = UpdateTenantRequest; // @public export interface DecodedIdToken { - // (undocumented) [key: string]: any; aud: string; auth_time: number; @@ -250,7 +248,7 @@ export interface EmailSignInProviderConfig { passwordRequired?: boolean; } -// @public (undocumented) +// @public export function getAuth(app?: App): Auth; // @public @@ -280,7 +278,7 @@ export interface ListUsersResult { users: UserRecord[]; } -// @public (undocumented) +// @public export interface MultiFactorConfig { factorIds?: AuthFactorType[]; state: MultiFactorConfigState; @@ -296,20 +294,15 @@ export interface MultiFactorCreateSettings { // @public export abstract class MultiFactorInfo { - // (undocumented) readonly displayName?: string; - // (undocumented) readonly enrollmentTime?: string; - // (undocumented) readonly factorId: string; - toJSON(): any; - // (undocumented) + toJSON(): object; readonly uid: string; } // @public export class MultiFactorSettings { - // (undocumented) enrolledFactors: MultiFactorInfo[]; toJSON(): any; } @@ -341,9 +334,8 @@ export interface PhoneIdentifier { // @public export class PhoneMultiFactorInfo extends MultiFactorInfo { - // (undocumented) readonly phoneNumber: string; - toJSON(): any; + toJSON(): object; } // @public @@ -381,15 +373,10 @@ export interface SessionCookieOptions { // @public export class Tenant { - // (undocumented) readonly displayName?: string; - // (undocumented) get emailSignInConfig(): EmailSignInProviderConfig | undefined; - // (undocumented) get multiFactorConfig(): MultiFactorConfig | undefined; - // (undocumented) readonly tenantId: string; - // (undocumented) readonly testPhoneNumbers?: { [phoneNumber: string]: string; }; @@ -399,7 +386,6 @@ export class Tenant { // @public export class TenantAwareAuth extends BaseAuth { createSessionCookie(idToken: string, sessionCookieOptions: SessionCookieOptions): Promise; - // (undocumented) readonly tenantId: string; verifyIdToken(idToken: string, checkRevoked?: boolean): Promise; verifySessionCookie(sessionCookie: string, checkRevoked?: boolean): Promise; @@ -505,27 +491,19 @@ export interface UserImportResult { // @public export class UserInfo { - // (undocumented) readonly displayName: string; - // (undocumented) readonly email: string; - // (undocumented) readonly phoneNumber: string; - // (undocumented) readonly photoURL: string; - // (undocumented) readonly providerId: string; toJSON(): object; - // (undocumented) readonly uid: string; } // @public export class UserMetadata { - // (undocumented) readonly creationTime: string; readonly lastRefreshTime: string | null; - // (undocumented) readonly lastSignInTime: string; toJSON(): object; } @@ -548,38 +526,23 @@ export interface UserProviderRequest { // @public export class UserRecord { - // (undocumented) - readonly customClaims: { + readonly customClaims?: { [key: string]: any; }; - // (undocumented) readonly disabled: boolean; - // (undocumented) - readonly displayName: string; - // (undocumented) - readonly email: string; - // (undocumented) + readonly displayName?: string; + readonly email?: string; readonly emailVerified: boolean; - // (undocumented) readonly metadata: UserMetadata; - // (undocumented) readonly multiFactor?: MultiFactorSettings; - // (undocumented) readonly passwordHash?: string; - // (undocumented) readonly passwordSalt?: string; - // (undocumented) - readonly phoneNumber: string; - // (undocumented) - readonly photoURL: string; - // (undocumented) + readonly phoneNumber?: string; + readonly photoURL?: string; readonly providerData: UserInfo[]; - // (undocumented) readonly tenantId?: string | null; toJSON(): object; - // (undocumented) readonly tokensValidAfterTime?: string; - // (undocumented) readonly uid: string; } diff --git a/src/auth/auth-config.ts b/src/auth/auth-config.ts index 1449d4191f..be6f2ccb6c 100644 --- a/src/auth/auth-config.ts +++ b/src/auth/auth-config.ts @@ -406,6 +406,11 @@ export type AuthFactorType = 'phone'; */ export type MultiFactorConfigState = 'ENABLED' | 'DISABLED'; +/** + * Interface representing a multi-factor configuration. + * This can be used to define whether multi-factor authentication is enabled + * or disabled and the list of second factor challenges that are supported. + */ export interface MultiFactorConfig { /** * The multi-factor config state. @@ -584,7 +589,7 @@ export function validateTestPhoneNumbers( } /** - * The email sign in configuration. + * The email sign in provider configuration. */ export interface EmailSignInProviderConfig { /** @@ -1010,7 +1015,7 @@ export class SAMLConfig implements SAMLAuthProviderConfig { /** * The SAMLConfig constructor. * - * @param {any} response The server side response used to initialize the SAMLConfig object. + * @param response The server side response used to initialize the SAMLConfig object. * @constructor */ constructor(response: SAMLConfigServerResponse) { @@ -1211,7 +1216,7 @@ export class OIDCConfig implements OIDCAuthProviderConfig { /** * The OIDCConfig constructor. * - * @param {any} response The server side response used to initialize the OIDCConfig object. + * @param response The server side response used to initialize the OIDCConfig object. * @constructor */ constructor(response: OIDCConfigServerResponse) { diff --git a/src/auth/auth-namespace.ts b/src/auth/auth-namespace.ts index d7830bd046..7924bcf479 100644 --- a/src/auth/auth-namespace.ts +++ b/src/auth/auth-namespace.ts @@ -95,6 +95,27 @@ import { UserRecord as TUserRecord, } from './user-record'; +/** + * Gets the {@link auth.Auth `Auth`} service for the default app or a + * given app. + * + * `getAuth()` can be called with no arguments to access the default app's + * {@link auth.Auth `Auth`} service or as `getAuth(app)` to access the + * {@link auth.Auth `Auth`} service associated with a specific app. + * + * @example + * ```javascript + * // Get the Auth service for the default app + * const defaultAuth = getAuth(); + * ``` + * + * @example + * ```javascript + * // Get the Auth service for a given app + * const otherAuth = getAuth(otherApp); + * ``` + * + */ export function getAuth(app?: App): Auth { if (typeof app === 'undefined') { app = getApp(); diff --git a/src/auth/auth.ts b/src/auth/auth.ts index 0378466b76..132631970f 100644 --- a/src/auth/auth.ts +++ b/src/auth/auth.ts @@ -49,7 +49,9 @@ export class Auth extends BaseAuth { return this.app_; } - /** @return The current Auth instance's tenant manager. */ + /** + * @return The tenant manager instance associated with the current project. + */ public tenantManager(): TenantManager { return this.tenantManager_; } diff --git a/src/auth/base-auth.ts b/src/auth/base-auth.ts index 502e4b2f1b..fd6dcd39c2 100644 --- a/src/auth/base-auth.ts +++ b/src/auth/base-auth.ts @@ -109,9 +109,9 @@ export interface SessionCookieOptions { } /** - * Base Auth class. Mainly used for user management APIs. + * Common parent interface for both `Auth` and `TenantAwareAuth` APIs. */ -export class BaseAuth { +export abstract class BaseAuth { /** @internal */ protected readonly tokenGenerator: FirebaseTokenGenerator; @@ -147,29 +147,44 @@ export class BaseAuth { } /** - * Creates a new custom token that can be sent back to a client to use with - * signInWithCustomToken(). + * Creates a new Firebase custom token (JWT) that can be sent back to a client + * device to use to sign in with the client SDKs' `signInWithCustomToken()` + * methods. (Tenant-aware instances will also embed the tenant ID in the + * token.) * - * @param {string} uid The uid to use as the JWT subject. - * @param {object=} developerClaims Optional additional claims to include in the JWT payload. + * See [Create Custom Tokens](/docs/auth/admin/create-custom-tokens) for code + * samples and detailed documentation. * - * @return {Promise} A JWT for the provided payload. + * @param uid The `uid` to use as the custom token's subject. + * @param developerClaims Optional additional claims to include + * in the custom token's payload. + * + * @return A promise fulfilled with a custom token for the + * provided `uid` and payload. */ public createCustomToken(uid: string, developerClaims?: object): Promise { return this.tokenGenerator.createCustomToken(uid, developerClaims); } /** - * Verifies a JWT auth token. Returns a Promise with the tokens claims. Rejects - * the promise if the token could not be verified. If checkRevoked is set to true, - * verifies if the session corresponding to the ID token was revoked. If the corresponding - * user's session was invalidated, an auth/id-token-revoked error is thrown. If not specified - * the check is not applied. + * Verifies a Firebase ID token (JWT). If the token is valid, the promise is + * fulfilled with the token's decoded claims; otherwise, the promise is + * rejected. + * An optional flag can be passed to additionally check whether the ID token + * was revoked. + * + * See [Verify ID Tokens](/docs/auth/admin/verify-id-tokens) for code samples + * and detailed documentation. + * + * @param idToken The ID token to verify. + * @param checkRevoked Whether to check if the ID token was revoked. + * This requires an extra request to the Firebase Auth backend to check + * the `tokensValidAfterTime` time for the corresponding user. + * When not specified, this additional check is not applied. * - * @param {string} idToken The JWT to verify. - * @param {boolean=} checkRevoked Whether to check if the ID token is revoked. - * @return {Promise} A Promise that will be fulfilled after a successful - * verification. + * @return A promise fulfilled with the + * token's decoded claims if the ID token is valid; otherwise, a rejected + * promise. */ public verifyIdToken(idToken: string, checkRevoked = false): Promise { return this.idTokenVerifier.verifyJWT(idToken) @@ -185,11 +200,15 @@ export class BaseAuth { } /** - * Looks up the user identified by the provided user id and returns a promise that is - * fulfilled with a user record for the given user if that user is found. + * Gets the user data for the user corresponding to a given `uid`. + * + * See [Retrieve user data](/docs/auth/admin/manage-users#retrieve_user_data) + * for code samples and detailed documentation. + * + * @param uid The `uid` corresponding to the user whose data to fetch. * - * @param {string} uid The uid of the user to look up. - * @return {Promise} A promise that resolves with the corresponding user record. + * @return A promise fulfilled with the user + * data corresponding to the provided `uid`. */ public getUser(uid: string): Promise { return this.authRequestHandler.getAccountInfoByUid(uid) @@ -200,11 +219,16 @@ export class BaseAuth { } /** - * Looks up the user identified by the provided email and returns a promise that is - * fulfilled with a user record for the given user if that user is found. + * Gets the user data for the user corresponding to a given email. * - * @param {string} email The email of the user to look up. - * @return {Promise} A promise that resolves with the corresponding user record. + * See [Retrieve user data](/docs/auth/admin/manage-users#retrieve_user_data) + * for code samples and detailed documentation. + * + * @param email The email corresponding to the user whose data to + * fetch. + * + * @return A promise fulfilled with the user + * data corresponding to the provided email. */ public getUserByEmail(email: string): Promise { return this.authRequestHandler.getAccountInfoByEmail(email) @@ -215,11 +239,17 @@ export class BaseAuth { } /** - * Looks up the user identified by the provided phone number and returns a promise that is - * fulfilled with a user record for the given user if that user is found. + * Gets the user data for the user corresponding to a given phone number. The + * phone number has to conform to the E.164 specification. + * + * See [Retrieve user data](/docs/auth/admin/manage-users#retrieve_user_data) + * for code samples and detailed documentation. * - * @param {string} phoneNumber The phone number of the user to look up. - * @return {Promise} A promise that resolves with the corresponding user record. + * @param phoneNumber The phone number corresponding to the user whose + * data to fetch. + * + * @return A promise fulfilled with the user + * data corresponding to the provided phone number. */ public getUserByPhoneNumber(phoneNumber: string): Promise { return this.authRequestHandler.getAccountInfoByPhoneNumber(phoneNumber) @@ -236,10 +266,10 @@ export class BaseAuth { * guaranteed to correspond to the nth entry in the input parameters list. * * Only a maximum of 100 identifiers may be supplied. If more than 100 identifiers are supplied, - * this method will immediately throw a FirebaseAuthError. + * this method throws a FirebaseAuthError. * - * @param identifiers The identifiers used to indicate which user records should be returned. Must - * have <= 100 entries. + * @param identifiers The identifiers used to indicate which user records should be returned. + * Must have <= 100 entries. * @return {Promise} A promise that resolves to the corresponding user records. * @throws FirebaseAuthError If any of the identifiers are invalid or if more than 100 * identifiers are specified. @@ -285,16 +315,19 @@ export class BaseAuth { } /** - * Exports a batch of user accounts. Batch size is determined by the maxResults argument. - * Starting point of the batch is determined by the pageToken argument. + * Retrieves a list of users (single batch only) with a size of `maxResults` + * starting from the offset as specified by `pageToken`. This is used to + * retrieve all the users of a specified project in batches. + * + * See [List all users](/docs/auth/admin/manage-users#list_all_users) + * for code samples and detailed documentation. * - * @param {number=} maxResults The page size, 1000 if undefined. This is also the maximum - * allowed limit. - * @param {string=} pageToken The next page token. If not specified, returns users starting - * without any offset. - * @return {Promise<{users: UserRecord[], pageToken?: string}>} A promise that resolves with - * the current batch of downloaded users and the next page token. For the last page, an - * empty list of users and no page token are returned. + * @param maxResults The page size, 1000 if undefined. This is also + * the maximum allowed limit. + * @param pageToken The next page token. If not specified, returns + * users starting without any offset. + * @return A promise that resolves with + * the current batch of downloaded users and the next page token. */ public listUsers(maxResults?: number, pageToken?: string): Promise { return this.authRequestHandler.downloadAccount(maxResults, pageToken) @@ -319,10 +352,16 @@ export class BaseAuth { } /** - * Creates a new user with the properties provided. + * Creates a new user. * - * @param {CreateRequest} properties The properties to set on the new user record to be created. - * @return {Promise} A promise that resolves with the newly created user record. + * See [Create a user](/docs/auth/admin/manage-users#create_a_user) for code + * samples and detailed documentation. + * + * @param properties The properties to set on the + * new user record to be created. + * + * @return A promise fulfilled with the user + * data corresponding to the newly created user. */ public createUser(properties: CreateRequest): Promise { return this.authRequestHandler.createNewAccount(properties) @@ -342,11 +381,15 @@ export class BaseAuth { } /** - * Deletes the user identified by the provided user id and returns a promise that is - * fulfilled when the user is found and successfully deleted. + * Deletes an existing user. + * + * See [Delete a user](/docs/auth/admin/manage-users#delete_a_user) for code + * samples and detailed documentation. * - * @param {string} uid The uid of the user to delete. - * @return {Promise} A promise that resolves when the user is successfully deleted. + * @param uid The `uid` corresponding to the user to delete. + * + * @return An empty promise fulfilled once the user has been + * deleted. */ public deleteUser(uid: string): Promise { return this.authRequestHandler.deleteAccount(uid) @@ -355,6 +398,28 @@ export class BaseAuth { }); } + /** + * Deletes the users specified by the given uids. + * + * Deleting a non-existing user won't generate an error (i.e. this method + * is idempotent.) Non-existing users are considered to be successfully + * deleted, and are therefore counted in the + * `DeleteUsersResult.successCount` value. + * + * Only a maximum of 1000 identifiers may be supplied. If more than 1000 + * identifiers are supplied, this method throws a FirebaseAuthError. + * + * This API is currently rate limited at the server to 1 QPS. If you exceed + * this, you may get a quota exceeded error. Therefore, if you want to + * delete more than 1000 users, you may need to add a delay to ensure you + * don't go over this limit. + * + * @param uids The `uids` corresponding to the users to delete. + * + * @return A Promise that resolves to the total number of successful/failed + * deletions, as well as the array of errors that corresponds to the + * failed deletions. + */ public deleteUsers(uids: string[]): Promise { if (!validator.isArray(uids)) { throw new FirebaseAuthError( @@ -400,11 +465,17 @@ export class BaseAuth { } /** - * Updates an existing user with the properties provided. + * Updates an existing user. + * + * See [Update a user](/docs/auth/admin/manage-users#update_a_user) for code + * samples and detailed documentation. + * + * @param uid The `uid` corresponding to the user to update. + * @param properties The properties to update on + * the provided user. * - * @param {string} uid The uid identifier of the user to update. - * @param {UpdateRequest} properties The properties to update on the existing user. - * @return {Promise} A promise that resolves with the modified user record. + * @return A promise fulfilled with the + * updated user data. */ public updateUser(uid: string, properties: UpdateRequest): Promise { return this.authRequestHandler.updateExistingAccount(uid, properties) @@ -415,12 +486,27 @@ export class BaseAuth { } /** - * Sets additional developer claims on an existing user identified by the provided UID. + * Sets additional developer claims on an existing user identified by the + * provided `uid`, typically used to define user roles and levels of + * access. These claims should propagate to all devices where the user is + * already signed in (after token expiration or when token refresh is forced) + * and the next time the user signs in. If a reserved OIDC claim name + * is used (sub, iat, iss, etc), an error is thrown. They are set on the + * authenticated user's ID token JWT. * - * @param {string} uid The user to edit. - * @param {object} customUserClaims The developer claims to set. - * @return {Promise} A promise that resolves when the operation completes - * successfully. + * See + * [Defining user roles and access levels](/docs/auth/admin/custom-claims) + * for code samples and detailed documentation. + * + * @param uid The `uid` of the user to edit. + * @param customUserClaims The developer claims to set. If null is + * passed, existing custom claims are deleted. Passing a custom claims payload + * larger than 1000 bytes will throw an error. Custom claims are added to the + * user's ID token which is transmitted on every authenticated request. + * For profile non-access related user attributes, use database or other + * separate storage systems. + * @return A promise that resolves when the operation completes + * successfully. */ public setCustomUserClaims(uid: string, customUserClaims: object | null): Promise { return this.authRequestHandler.setCustomUserClaims(uid, customUserClaims) @@ -430,14 +516,25 @@ export class BaseAuth { } /** - * Revokes all refresh tokens for the specified user identified by the provided UID. - * In addition to revoking all refresh tokens for a user, all ID tokens issued before - * revocation will also be revoked on the Auth backend. Any request with an ID token - * generated before revocation will be rejected with a token expired error. + * Revokes all refresh tokens for an existing user. + * + * This API will update the user's + * {@link auth.UserRecord.tokensValidAfterTime `tokensValidAfterTime`} to + * the current UTC. It is important that the server on which this is called has + * its clock set correctly and synchronized. * - * @param {string} uid The user whose tokens are to be revoked. - * @return {Promise} A promise that resolves when the operation completes - * successfully. + * While this will revoke all sessions for a specified user and disable any + * new ID tokens for existing sessions from getting minted, existing ID tokens + * may remain active until their natural expiration (one hour). To verify that + * ID tokens are revoked, use + * {@link auth.Auth.verifyIdToken `verifyIdToken(idToken, true)`} + * where `checkRevoked` is set to true. + * + * @param uid The `uid` corresponding to the user whose refresh tokens + * are to be revoked. + * + * @return An empty promise fulfilled once the user's refresh + * tokens have been revoked. */ public revokeRefreshTokens(uid: string): Promise { return this.authRequestHandler.revokeRefreshTokens(uid) @@ -447,33 +544,43 @@ export class BaseAuth { } /** - * Imports the list of users provided to Firebase Auth. This is useful when - * migrating from an external authentication system without having to use the Firebase CLI SDK. - * At most, 1000 users are allowed to be imported one at a time. - * When importing a list of password users, UserImportOptions are required to be specified. + * Imports the provided list of users into Firebase Auth. + * A maximum of 1000 users are allowed to be imported one at a time. + * When importing users with passwords, + * {@link auth.UserImportOptions `UserImportOptions`} are required to be + * specified. + * This operation is optimized for bulk imports and will ignore checks on `uid`, + * `email` and other identifier uniqueness which could result in duplications. * - * @param {UserImportRecord[]} users The list of user records to import to Firebase Auth. - * @param {UserImportOptions=} options The user import options, required when the users provided - * include password credentials. - * @return {Promise} A promise that resolves when the operation completes - * with the result of the import. This includes the number of successful imports, the number - * of failed uploads and their corresponding errors. - */ + * @param users The list of user records to import to Firebase Auth. + * @param options The user import options, required when the users provided include + * password credentials. + * @return A promise that resolves when + * the operation completes with the result of the import. This includes the + * number of successful imports, the number of failed imports and their + * corresponding errors. + */ public importUsers( users: UserImportRecord[], options?: UserImportOptions): Promise { return this.authRequestHandler.uploadAccount(users, options); } /** - * Creates a new Firebase session cookie with the specified options that can be used for - * session management (set as a server side session cookie with custom cookie policy). - * The session cookie JWT will have the same payload claims as the provided ID token. + * Creates a new Firebase session cookie with the specified options. The created + * JWT string can be set as a server-side session cookie with a custom cookie + * policy, and be used for session management. The session cookie JWT will have + * the same payload claims as the provided ID token. * - * @param {string} idToken The Firebase ID token to exchange for a session cookie. - * @param {SessionCookieOptions} sessionCookieOptions The session cookie options which includes - * custom session duration. + * See [Manage Session Cookies](/docs/auth/admin/manage-cookies) for code + * samples and detailed documentation. * - * @return {Promise} A promise that resolves on success with the created session cookie. + * @param idToken The Firebase ID token to exchange for a session + * cookie. + * @param sessionCookieOptions The session + * cookie options which includes custom session duration. + * + * @return A promise that resolves on success with the + * created session cookie. */ public createSessionCookie( idToken: string, sessionCookieOptions: SessionCookieOptions): Promise { @@ -487,16 +594,25 @@ export class BaseAuth { } /** - * Verifies a Firebase session cookie. Returns a Promise with the tokens claims. Rejects - * the promise if the token could not be verified. If checkRevoked is set to true, - * verifies if the session corresponding to the session cookie was revoked. If the corresponding - * user's session was invalidated, an auth/session-cookie-revoked error is thrown. If not - * specified the check is not performed. + * Verifies a Firebase session cookie. Returns a Promise with the cookie claims. + * Rejects the promise if the cookie could not be verified. If `checkRevoked` is + * set to true, verifies if the session corresponding to the session cookie was + * revoked. If the corresponding user's session was revoked, an + * `auth/session-cookie-revoked` error is thrown. If not specified the check is + * not performed. + * + * See [Verify Session Cookies](/docs/auth/admin/manage-cookies#verify_session_cookie_and_check_permissions) + * for code samples and detailed documentation * - * @param {string} sessionCookie The session cookie to verify. - * @param {boolean=} checkRevoked Whether to check if the session cookie is revoked. - * @return {Promise} A Promise that will be fulfilled after a successful - * verification. + * @param sessionCookie The session cookie to verify. + * @param checkForRevocation Whether to check if the session cookie was + * revoked. This requires an extra request to the Firebase Auth backend to + * check the `tokensValidAfterTime` time for the corresponding user. + * When not specified, this additional check is not performed. + * + * @return A promise fulfilled with the + * session cookie's decoded claims if the session cookie is valid; otherwise, + * a rejected promise. */ public verifySessionCookie( sessionCookie: string, checkRevoked = false): Promise { @@ -513,57 +629,175 @@ export class BaseAuth { } /** - * Generates the out of band email action link for password reset flows for the - * email specified using the action code settings provided. - * Returns a promise that resolves with the generated link. + * Generates the out of band email action link to reset a user's password. + * The link is generated for the user with the specified email address. The + * optional {@link auth.ActionCodeSettings `ActionCodeSettings`} object + * defines whether the link is to be handled by a mobile app or browser and the + * additional state information to be passed in the deep link, etc. + * + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/?email=user@example.com', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * dynamicLinkDomain: 'custom.page.link' + * }; + * admin.auth() + * .generatePasswordResetLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` * - * @param {string} email The email of the user whose password is to be reset. - * @param {ActionCodeSettings=} actionCodeSettings The optional action code setings which defines whether - * the link is to be handled by a mobile app and the additional state information to be passed in the - * deep link, etc. - * @return {Promise} A promise that resolves with the password reset link. + * @param email The email address of the user whose password is to be + * reset. + * @param actionCodeSettings The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the password reset link. The default password + * reset landing page will use this to display a link to go back to the app + * if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @return A promise that resolves with the generated link. */ public generatePasswordResetLink(email: string, actionCodeSettings?: ActionCodeSettings): Promise { return this.authRequestHandler.getEmailActionLink('PASSWORD_RESET', email, actionCodeSettings); } /** - * Generates the out of band email action link for email verification flows for the - * email specified using the action code settings provided. - * Returns a promise that resolves with the generated link. + * Generates the out of band email action link to verify the user's ownership + * of the specified email. The + * {@link auth.ActionCodeSettings `ActionCodeSettings`} object provided + * as an argument to this method defines whether the link is to be handled by a + * mobile app or browser along with additional state information to be passed in + * the deep link, etc. + * + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * dynamicLinkDomain: 'custom.page.link' + * }; + * admin.auth() + * .generateEmailVerificationLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` * - * @param {string} email The email of the user to be verified. - * @param {ActionCodeSettings=} actionCodeSettings The optional action code setings which defines whether - * the link is to be handled by a mobile app and the additional state information to be passed in the - * deep link, etc. - * @return {Promise} A promise that resolves with the email verification link. + * @param email The email account to verify. + * @param actionCodeSettings The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the email verification link. The default email + * verification landing page will use this to display a link to go back to + * the app if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @return A promise that resolves with the generated link. */ public generateEmailVerificationLink(email: string, actionCodeSettings?: ActionCodeSettings): Promise { return this.authRequestHandler.getEmailActionLink('VERIFY_EMAIL', email, actionCodeSettings); } /** - * Generates the out of band email action link for email link sign-in flows for the - * email specified using the action code settings provided. - * Returns a promise that resolves with the generated link. + * Generates the out of band email action link to verify the user's ownership + * of the specified email. The + * {@link auth.ActionCodeSettings `ActionCodeSettings`} object provided + * as an argument to this method defines whether the link is to be handled by a + * mobile app or browser along with additional state information to be passed in + * the deep link, etc. * - * @param {string} email The email of the user signing in. - * @param {ActionCodeSettings} actionCodeSettings The required action code setings which defines whether - * the link is to be handled by a mobile app and the additional state information to be passed in the - * deep link, etc. - * @return {Promise} A promise that resolves with the email sign-in link. + * @example + * ```javascript + * var actionCodeSettings = { + * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', + * iOS: { + * bundleId: 'com.example.ios' + * }, + * android: { + * packageName: 'com.example.android', + * installApp: true, + * minimumVersion: '12' + * }, + * handleCodeInApp: true, + * dynamicLinkDomain: 'custom.page.link' + * }; + * admin.auth() + * .generateEmailVerificationLink('user@example.com', actionCodeSettings) + * .then(function(link) { + * // The link was successfully generated. + * }) + * .catch(function(error) { + * // Some error occurred, you can inspect the code: error.code + * }); + * ``` + * + * @param email The email account to verify. + * @param actionCodeSettings The action + * code settings. If specified, the state/continue URL is set as the + * "continueUrl" parameter in the email verification link. The default email + * verification landing page will use this to display a link to go back to + * the app if it is installed. + * If the actionCodeSettings is not specified, no URL is appended to the + * action URL. + * The state URL provided must belong to a domain that is whitelisted by the + * developer in the console. Otherwise an error is thrown. + * Mobile app redirects are only applicable if the developer configures + * and accepts the Firebase Dynamic Links terms of service. + * The Android package name and iOS bundle ID are respected only if they + * are configured in the same Firebase Auth project. + * @return A promise that resolves with the generated link. */ public generateSignInWithEmailLink(email: string, actionCodeSettings: ActionCodeSettings): Promise { return this.authRequestHandler.getEmailActionLink('EMAIL_SIGNIN', email, actionCodeSettings); } /** - * Returns the list of existing provider configuation matching the filter provided. - * At most, 100 provider configs are allowed to be imported at a time. + * Returns the list of existing provider configurations matching the filter + * provided. At most, 100 provider configs can be listed at a time. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the [GCIP documentation](https://cloud.google.com/identity-platform). * - * @param {AuthProviderConfigFilter} options The provider config filter to apply. - * @return {Promise} A promise that resolves with the list of provider configs - * meeting the filter requirements. + * @param options The provider config filter to apply. + * @return A promise that resolves with the list of provider configs meeting the + * filter requirements. */ public listProviderConfigs(options: AuthProviderConfigFilter): Promise { const processResponse = (response: any, providerConfigs: AuthProviderConfig[]): ListProviderConfigResults => { @@ -609,11 +843,19 @@ export class BaseAuth { } /** - * Looks up an Auth provider configuration by ID. - * Returns a promise that resolves with the provider configuration corresponding to the provider ID specified. + * Looks up an Auth provider configuration by the provided ID. + * Returns a promise that resolves with the provider configuration + * corresponding to the provider ID specified. If the specified ID does not + * exist, an `auth/configuration-not-found` error is thrown. * - * @param {string} providerId The provider ID corresponding to the provider config to return. - * @return {Promise} + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the [GCIP documentation](https://cloud.google.com/identity-platform). + * + * @param providerId The provider ID corresponding to the provider + * config to return. + * @return A promise that resolves + * with the configuration corresponding to the provided ID. */ public getProviderConfig(providerId: string): Promise { if (OIDCConfig.isProviderId(providerId)) { @@ -632,9 +874,16 @@ export class BaseAuth { /** * Deletes the provider configuration corresponding to the provider ID passed. + * If the specified ID does not exist, an `auth/configuration-not-found` error + * is thrown. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the [GCIP documentation](https://cloud.google.com/identity-platform). * - * @param {string} providerId The provider ID corresponding to the provider config to delete. - * @return {Promise} A promise that resolves on completion. + * @param providerId The provider ID corresponding to the provider + * config to delete. + * @return A promise that resolves on completion. */ public deleteProviderConfig(providerId: string): Promise { if (OIDCConfig.isProviderId(providerId)) { @@ -646,12 +895,19 @@ export class BaseAuth { } /** - * Returns a promise that resolves with the updated AuthProviderConfig when the provider configuration corresponding - * to the provider ID specified is updated with the specified configuration. + * Returns a promise that resolves with the updated `AuthProviderConfig` + * corresponding to the provider ID specified. + * If the specified ID does not exist, an `auth/configuration-not-found` error + * is thrown. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the [GCIP documentation](https://cloud.google.com/identity-platform). * - * @param {string} providerId The provider ID corresponding to the provider config to update. - * @param {UpdateAuthProviderRequest} updatedConfig The updated configuration. - * @return {Promise} A promise that resolves with the updated provider configuration. + * @param providerId The provider ID corresponding to the provider + * config to update. + * @param updatedConfig The updated configuration. + * @return A promise that resolves with the updated provider configuration. */ public updateProviderConfig( providerId: string, updatedConfig: UpdateAuthProviderRequest): Promise { @@ -676,10 +932,15 @@ export class BaseAuth { } /** - * Returns a promise that resolves with the newly created AuthProviderConfig when the new provider configuration is - * created. - * @param {AuthProviderConfig} config The provider configuration to create. - * @return {Promise} A promise that resolves with the created provider configuration. + * Returns a promise that resolves with the newly created `AuthProviderConfig` + * when the new provider configuration is created. + * + * SAML and OIDC provider support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the [GCIP documentation](https://cloud.google.com/identity-platform). + * + * @param config The provider configuration to create. + * @return A promise that resolves with the created provider configuration. */ public createProviderConfig(config: AuthProviderConfig): Promise { if (!validator.isNonNullObject(config)) { @@ -706,11 +967,10 @@ export class BaseAuth { * Verifies the decoded Firebase issued JWT is not revoked. Returns a promise that resolves * with the decoded claims on success. Rejects the promise with revocation error if revoked. * - * @param {DecodedIdToken} decodedIdToken The JWT's decoded claims. - * @param {ErrorInfo} revocationErrorInfo The revocation error info to throw on revocation + * @param decodedIdToken The JWT's decoded claims. + * @param revocationErrorInfo The revocation error info to throw on revocation * detection. - * @return {Promise} A Promise that will be fulfilled after a successful - * verification. + * @return A Promise that will be fulfilled after a successful verification. */ private verifyDecodedJWTNotRevoked( decodedIdToken: DecodedIdToken, revocationErrorInfo: ErrorInfo): Promise { diff --git a/src/auth/identifier.ts b/src/auth/identifier.ts index 709ff81a06..8db37c36b4 100644 --- a/src/auth/identifier.ts +++ b/src/auth/identifier.ts @@ -17,7 +17,7 @@ /** * Used for looking up an account by uid. * - * See auth.getUsers() + * See `auth.getUsers()` */ export interface UidIdentifier { uid: string; @@ -26,7 +26,7 @@ export interface UidIdentifier { /** * Used for looking up an account by email. * - * See auth.getUsers() + * See `auth.getUsers()` */ export interface EmailIdentifier { email: string; @@ -35,7 +35,7 @@ export interface EmailIdentifier { /** * Used for looking up an account by phone number. * - * See auth.getUsers() + * See `auth.getUsers()` */ export interface PhoneIdentifier { phoneNumber: string; @@ -44,7 +44,7 @@ export interface PhoneIdentifier { /** * Used for looking up an account by federated provider. * - * See auth.getUsers() + * See `auth.getUsers()` */ export interface ProviderIdentifier { providerId: string; diff --git a/src/auth/tenant-manager.ts b/src/auth/tenant-manager.ts index e58f803615..2878ed907c 100644 --- a/src/auth/tenant-manager.ts +++ b/src/auth/tenant-manager.ts @@ -47,16 +47,35 @@ export interface ListTenantsResult { } /** - * The tenant aware Auth class. + * Tenant-aware `Auth` interface used for managing users, configuring SAML/OIDC providers, + * generating email links for password reset, email verification, etc for specific tenants. + * + * Multi-tenancy support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the [GCIP documentation](https://cloud.google.com/identity-platform) + * + * Each tenant contains its own identity providers, settings and sets of users. + * Using `TenantAwareAuth`, users for a specific tenant and corresponding OIDC/SAML + * configurations can also be managed, ID tokens for users signed in to a specific tenant + * can be verified, and email action links can also be generated for users belonging to the + * tenant. + * + * `TenantAwareAuth` instances for a specific `tenantId` can be instantiated by calling + * `auth.tenantManager().authForTenant(tenantId)`. */ export class TenantAwareAuth extends BaseAuth { + /** + * The tenant identifier corresponding to this `TenantAwareAuth` instance. + * All calls to the user management APIs, OIDC/SAML provider management APIs, email link + * generation APIs, etc will only be applied within the scope of this tenant. + */ public readonly tenantId: string; /** * The TenantAwareAuth class constructor. * - * @param {object} app The app that created this tenant. + * @param app The app that created this tenant. * @param tenantId The corresponding tenant ID. * @constructor * @internal @@ -69,16 +88,7 @@ export class TenantAwareAuth extends BaseAuth { } /** - * Verifies a JWT auth token. Returns a Promise with the tokens claims. Rejects - * the promise if the token could not be verified. If checkRevoked is set to true, - * verifies if the session corresponding to the ID token was revoked. If the corresponding - * user's session was invalidated, an auth/id-token-revoked error is thrown. If not specified - * the check is not applied. - * - * @param {string} idToken The JWT to verify. - * @param {boolean=} checkRevoked Whether to check if the ID token is revoked. - * @return {Promise} A Promise that will be fulfilled after a successful - * verification. + * {@inheritdoc BaseAuth.verifyIdToken} */ public verifyIdToken(idToken: string, checkRevoked = false): Promise { return super.verifyIdToken(idToken, checkRevoked) @@ -92,15 +102,7 @@ export class TenantAwareAuth extends BaseAuth { } /** - * Creates a new Firebase session cookie with the specified options that can be used for - * session management (set as a server side session cookie with custom cookie policy). - * The session cookie JWT will have the same payload claims as the provided ID token. - * - * @param {string} idToken The Firebase ID token to exchange for a session cookie. - * @param {SessionCookieOptions} sessionCookieOptions The session cookie options which includes - * custom session duration. - * - * @return {Promise} A promise that resolves on success with the created session cookie. + * {@inheritdoc BaseAuth.createSessionCookie} */ public createSessionCookie( idToken: string, sessionCookieOptions: SessionCookieOptions): Promise { @@ -120,16 +122,7 @@ export class TenantAwareAuth extends BaseAuth { } /** - * Verifies a Firebase session cookie. Returns a Promise with the tokens claims. Rejects - * the promise if the token could not be verified. If checkRevoked is set to true, - * verifies if the session corresponding to the session cookie was revoked. If the corresponding - * user's session was invalidated, an auth/session-cookie-revoked error is thrown. If not - * specified the check is not performed. - * - * @param {string} sessionCookie The session cookie to verify. - * @param {boolean=} checkRevoked Whether to check if the session cookie is revoked. - * @return {Promise} A Promise that will be fulfilled after a successful - * verification. + * {@inheritdoc BaseAuth.verifySessionCookie} */ public verifySessionCookie( sessionCookie: string, checkRevoked = false): Promise { @@ -144,11 +137,15 @@ export class TenantAwareAuth extends BaseAuth { } /** - * Data structure used to help manage tenant related operations. + * Defines the tenant manager used to help manage tenant related operations. * This includes: - * - The ability to create, update, list, get and delete tenants for the underlying project. - * - Getting a TenantAwareAuth instance for running Auth related operations (user mgmt, provider config mgmt, etc) - * in the context of a specified tenant. + *
    + *
  • The ability to create, update, list, get and delete tenants for the underlying + * project.
  • + *
  • Getting a `TenantAwareAuth` instance for running Auth related operations + * (user management, provider configuration management, token verification, + * email link generation, etc) in the context of a specified tenant.
  • + *
*/ export class TenantManager { private readonly authRequestHandler: AuthRequestHandler; @@ -168,10 +165,11 @@ export class TenantManager { } /** - * Returns a TenantAwareAuth instance for the corresponding tenant ID. + * Returns a `TenantAwareAuth` instance bound to the given tenant ID. + * + * @param tenantId The tenant ID whose `TenantAwareAuth` instance is to be returned. * - * @param tenantId The tenant ID whose TenantAwareAuth is to be returned. - * @return The corresponding TenantAwareAuth instance. + * @return The `TenantAwareAuth` instance corresponding to this tenant identifier. */ public authForTenant(tenantId: string): TenantAwareAuth { if (!validator.isNonEmptyString(tenantId)) { @@ -184,11 +182,11 @@ export class TenantManager { } /** - * Looks up the tenant identified by the provided tenant ID and returns a promise that is - * fulfilled with the corresponding tenant if it is found. + * Gets the tenant configuration for the tenant corresponding to a given `tenantId`. * - * @param tenantId The tenant ID of the tenant to look up. - * @return A promise that resolves with the corresponding tenant. + * @param tenantId The tenant identifier corresponding to the tenant whose data to fetch. + * + * @return A promise fulfilled with the tenant configuration to the provided `tenantId`. */ public getTenant(tenantId: string): Promise { return this.authRequestHandler.getTenant(tenantId) @@ -198,16 +196,17 @@ export class TenantManager { } /** - * Exports a batch of tenant accounts. Batch size is determined by the maxResults argument. - * Starting point of the batch is determined by the pageToken argument. + * Retrieves a list of tenants (single batch only) with a size of `maxResults` + * starting from the offset as specified by `pageToken`. This is used to + * retrieve all the tenants of a specified project in batches. + * + * @param maxResults The page size, 1000 if undefined. This is also + * the maximum allowed limit. + * @param pageToken The next page token. If not specified, returns + * tenants starting without any offset. * - * @param maxResults The page size, 1000 if undefined. This is also the maximum - * allowed limit. - * @param pageToken The next page token. If not specified, returns users starting - * without any offset. * @return A promise that resolves with - * the current batch of downloaded tenants and the next page token. For the last page, an - * empty list of tenants and no page token are returned. + * a batch of downloaded tenants and the next page token. */ public listTenants( maxResults?: number, @@ -234,21 +233,25 @@ export class TenantManager { } /** - * Deletes the tenant identified by the provided tenant ID and returns a promise that is - * fulfilled when the tenant is found and successfully deleted. + * Deletes an existing tenant. * - * @param tenantId The tenant ID of the tenant to delete. - * @return A promise that resolves when the tenant is successfully deleted. + * @param tenantId The `tenantId` corresponding to the tenant to delete. + * + * @return An empty promise fulfilled once the tenant has been deleted. */ public deleteTenant(tenantId: string): Promise { return this.authRequestHandler.deleteTenant(tenantId); } /** - * Creates a new tenant with the properties provided. + * Creates a new tenant. + * When creating new tenants, tenants that use separate billing and quota will require their + * own project and must be defined as `full_service`. + * + * @param tenantOptions The properties to set on the new tenant configuration to be created. * - * @param tenantOptions The properties to set on the new tenant to be created. - * @return A promise that resolves with the newly created tenant. + * @return A promise fulfilled with the tenant configuration corresponding to the newly + * created tenant. */ public createTenant(tenantOptions: CreateTenantRequest): Promise { return this.authRequestHandler.createTenant(tenantOptions) @@ -258,11 +261,12 @@ export class TenantManager { } /** - * Updates an existing tenant identified by the tenant ID with the properties provided. + * Updates an existing tenant configuration. + * + * @param tenantId The `tenantId` corresponding to the tenant to delete. + * @param tenantOptions The properties to update on the provided tenant. * - * @param tenantId The tenant identifier of the tenant to update. - * @param tenantOptions The properties to update on the existing tenant. - * @return A promise that resolves with the modified tenant. + * @return A promise fulfilled with the update tenant data. */ public updateTenant(tenantId: string, tenantOptions: UpdateTenantRequest): Promise { return this.authRequestHandler.updateTenant(tenantId, tenantOptions) diff --git a/src/auth/tenant.ts b/src/auth/tenant.ts index 8bbc0438c8..70b9daeb95 100644 --- a/src/auth/tenant.ts +++ b/src/auth/tenant.ts @@ -75,22 +75,51 @@ export interface TenantServerResponse { } /** - * Tenant class that defines a Firebase Auth tenant. + * Represents a tenant configuration. + * + * Multi-tenancy support requires Google Cloud's Identity Platform + * (GCIP). To learn more about GCIP, including pricing and features, + * see the [GCIP documentation](https://cloud.google.com/identity-platform) + * + * Before multi-tenancy can be used on a Google Cloud Identity Platform project, + * tenants must be allowed on that project via the Cloud Console UI. + * + * A tenant configuration provides information such as the display name, tenant + * identifier and email authentication configuration. + * For OIDC/SAML provider configuration management, `TenantAwareAuth` instances should + * be used instead of a `Tenant` to retrieve the list of configured IdPs on a tenant. + * When configuring these providers, note that tenants will inherit + * whitelisted domains and authenticated redirect URIs of their parent project. + * + * All other settings of a tenant will also be inherited. These will need to be managed + * from the Cloud Console UI. */ export class Tenant { + /** + * The tenant identifier. + */ public readonly tenantId: string; + + /** + * The tenant display name. + */ public readonly displayName?: string; + + /** + * The map containing the test phone number / code pairs for the tenant. + */ + public readonly testPhoneNumbers?: {[phoneNumber: string]: string}; + private readonly emailSignInConfig_?: EmailSignInConfig; private readonly multiFactorConfig_?: MultiFactorAuthConfig; - public readonly testPhoneNumbers?: {[phoneNumber: string]: string}; /** * Builds the corresponding server request for a TenantOptions object. * - * @param {TenantOptions} tenantOptions The properties to convert to a server request. - * @param {boolean} createRequest Whether this is a create request. - * @return {object} The equivalent server request. + * @param tenantOptions The properties to convert to a server request. + * @param createRequest Whether this is a create request. + * @return The equivalent server request. * * @internal */ @@ -224,15 +253,23 @@ export class Tenant { } } + /** + * The email sign in provider configuration. + */ get emailSignInConfig(): EmailSignInProviderConfig | undefined { return this.emailSignInConfig_; } + /** + * The multi-factor auth configuration on the current tenant. + */ get multiFactorConfig(): MultiFactorConfig | undefined { return this.multiFactorConfig_; } - /** @return {object} The plain object representation of the tenant. */ + /** + * @return A JSON-serializable representation of this object. + */ public toJSON(): object { const json = { tenantId: this.tenantId, diff --git a/src/auth/token-verifier.ts b/src/auth/token-verifier.ts index 99c6372687..71ba252c4e 100644 --- a/src/auth/token-verifier.ts +++ b/src/auth/token-verifier.ts @@ -167,6 +167,10 @@ export interface DecodedIdToken { * convenience, and is set as the value of the [`sub`](#sub) property. */ uid: string; + + /** + * Other arbitrary claims included in the ID token. + */ [key: string]: any; } diff --git a/src/auth/user-record.ts b/src/auth/user-record.ts index 149b2f89e5..86dadc07f9 100644 --- a/src/auth/user-record.ts +++ b/src/auth/user-record.ts @@ -86,12 +86,28 @@ enum MultiFactorId { } /** - * Abstract class representing a multi-factor info interface. + * Interface representing the common properties of a user enrolled second factor. */ export abstract class MultiFactorInfo { + + /** + * The ID of the enrolled second factor. This ID is unique to the user. + */ public readonly uid: string; + + /** + * The optional display name of the enrolled second factor. + */ public readonly displayName?: string; + + /** + * The type identifier of the second factor. For SMS second factors, this is `phone`. + */ public readonly factorId: string; + + /** + * The optional date the second factor was enrolled, formatted as a UTC string. + */ public readonly enrollmentTime?: string; /** @@ -123,8 +139,10 @@ export abstract class MultiFactorInfo { this.initFromServerResponse(response); } - /** @return The plain object representation. */ - public toJSON(): any { + /** + * @return A JSON-serializable representation of this object. + */ + public toJSON(): object { return { uid: this.uid, displayName: this.displayName, @@ -172,8 +190,14 @@ export abstract class MultiFactorInfo { } } -/** Class representing a phone MultiFactorInfo object. */ +/** + * Interface representing a phone specific user enrolled second factor. + */ export class PhoneMultiFactorInfo extends MultiFactorInfo { + + /** + * The phone number associated with a phone second factor. + */ public readonly phoneNumber: string; /** @@ -188,8 +212,10 @@ export class PhoneMultiFactorInfo extends MultiFactorInfo { utils.addReadonlyGetter(this, 'phoneNumber', response.phoneInfo); } - /** @return The plain object representation. */ - public toJSON(): any { + /** + * {@inheritdoc MultiFactorInfo.toJSON} + */ + public toJSON(): object { return Object.assign( super.toJSON(), { @@ -211,8 +237,15 @@ export class PhoneMultiFactorInfo extends MultiFactorInfo { } } -/** Class representing multi-factor related properties of a user. */ +/** + * The multi-factor related user settings. + */ export class MultiFactorSettings { + + /** + * List of second factors enrolled with the current user. + * Currently only phone second factors are supported. + */ public enrolledFactors: MultiFactorInfo[]; /** @@ -241,7 +274,9 @@ export class MultiFactorSettings { this, 'enrolledFactors', Object.freeze(parsedEnrolledFactors)); } - /** @return The plain object representation. */ + /** + * @return A JSON-serializable representation of this multi-factor object. + */ public toJSON(): any { return { enrolledFactors: this.enrolledFactors.map((info) => info.toJSON()), @@ -250,17 +285,24 @@ export class MultiFactorSettings { } /** - * User metadata class that provides metadata information like user account creation - * and last sign in time. + * Represents a user's metadata. */ export class UserMetadata { + + /** + * The date the user was created, formatted as a UTC string. + */ public readonly creationTime: string; + + /** + * The date the user last signed in, formatted as a UTC string. + */ public readonly lastSignInTime: string; /** - * The time at which the user was last active (ID token refreshed), or null - * if the user was never active. Formatted as a UTC Date string (eg - * 'Sat, 03 Feb 2001 04:05:06 GMT') + * The time at which the user was last active (ID token refreshed), + * formatted as a UTC Date string (eg 'Sat, 03 Feb 2001 04:05:06 GMT'). + * Returns null if the user was never active. */ public readonly lastRefreshTime: string | null; @@ -281,7 +323,9 @@ export class UserMetadata { utils.addReadonlyGetter(this, 'lastRefreshTime', lastRefreshAt); } - /** @return The plain object representation of the user's metadata. */ + /** + * @return A JSON-serializable representation of this object. + */ public toJSON(): object { return { lastSignInTime: this.lastSignInTime, @@ -291,15 +335,39 @@ export class UserMetadata { } /** - * User info class that provides provider user information for different - * Firebase providers like google.com, facebook.com, password, etc. + * Represents a user's info from a third-party identity provider + * such as Google or Facebook. */ export class UserInfo { + + /** + * The user identifier for the linked provider. + */ public readonly uid: string; + + /** + * The display name for the linked provider. + */ public readonly displayName: string; + + /** + * The email for the linked provider. + */ public readonly email: string; + + /** + * The photo URL for the linked provider. + */ public readonly photoURL: string; + + /** + * The linked provider ID (for example, "google.com" for the Google provider). + */ public readonly providerId: string; + + /** + * The phone number for the linked provider. + */ public readonly phoneNumber: string; @@ -325,7 +393,9 @@ export class UserInfo { utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber); } - /** @return The plain object representation of the current provider data. */ + /** + * @return A JSON-serializable representation of this object. + */ public toJSON(): object { return { uid: this.uid, @@ -339,28 +409,101 @@ export class UserInfo { } /** - * User record class that defines the Firebase user object populated from - * the Firebase Auth getAccountInfo response. - * - * @param response The server side response returned from the getAccountInfo - * endpoint. - * @constructor + * Represents a user. */ export class UserRecord { + + /** + * The user's `uid`. + */ public readonly uid: string; - public readonly email: string; + + /** + * The user's primary email, if set. + */ + public readonly email?: string; + + /** + * Whether or not the user's primary email is verified. + */ public readonly emailVerified: boolean; - public readonly displayName: string; - public readonly photoURL: string; - public readonly phoneNumber: string; + + /** + * The user's display name. + */ + public readonly displayName?: string; + + /** + * The user's photo URL. + */ + public readonly photoURL?: string; + + /** + * The user's primary phone number, if set. + */ + public readonly phoneNumber?: string; + + /** + * Whether or not the user is disabled: `true` for disabled; `false` for + * enabled. + */ public readonly disabled: boolean; + + /** + * Additional metadata about the user. + */ public readonly metadata: UserMetadata; + + /** + * An array of providers (for example, Google, Facebook) linked to the user. + */ public readonly providerData: UserInfo[]; + + /** + * The user's hashed password (base64-encoded), only if Firebase Auth hashing + * algorithm (SCRYPT) is used. If a different hashing algorithm had been used + * when uploading this user, as is typical when migrating from another Auth + * system, this will be an empty string. If no password is set, this is + * null. This is only available when the user is obtained from + * {@link auth.Auth.listUsers `listUsers()`}. + */ public readonly passwordHash?: string; + + /** + * The user's password salt (base64-encoded), only if Firebase Auth hashing + * algorithm (SCRYPT) is used. If a different hashing algorithm had been used to + * upload this user, typical when migrating from another Auth system, this will + * be an empty string. If no password is set, this is null. This is only + * available when the user is obtained from + * {@link auth.Auth.listUsers `listUsers()`}. + */ public readonly passwordSalt?: string; - public readonly customClaims: {[key: string]: any}; + + /** + * The user's custom claims object if available, typically used to define + * user roles and propagated to an authenticated user's ID token. + * This is set via + * {@link auth.Auth.setCustomUserClaims `setCustomUserClaims()`} + */ + public readonly customClaims?: {[key: string]: any}; + + /** + * The ID of the tenant the user belongs to, if available. + */ public readonly tenantId?: string | null; + + /** + * The date the user's tokens are valid after, formatted as a UTC string. + * This is updated every time the user's refresh token are revoked either + * from the {@link auth.Auth.revokeRefreshTokens `revokeRefreshTokens()`} + * API or from the Firebase Auth backend on big account changes (password + * resets, password or email updates, etc). + */ public readonly tokensValidAfterTime?: string; + + /** + * The multi-factor related properties for the current user, if available. + */ public readonly multiFactor?: MultiFactorSettings; /** @@ -420,7 +563,9 @@ export class UserRecord { } } - /** @return The plain object representation of the user record. */ + /** + * @return A JSON-serializable representation of this object. + */ public toJSON(): object { const json: any = { uid: this.uid,