firebase::auth::Auth

#include <auth.h>

Firebase authentication object.

Summary

firebase::auth::Auth is the gateway to the Firebase authentication API. With it, you can reference firebase::auth::User objects to manage user accounts and credentials.

Each firebase::App has up to one firebase::auth::Auth class. You acquire the firebase::auth::Auth class through the static function firebase::auth::Auth::GetAuth.

For example:

// Get the Auth class for your App.
firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);

// Request anonymous sign-in and wait until asynchronous call completes.
firebase::Future sign_in_future =
    auth->SignInAnonymously();
while (sign_in_future.status() == firebase::kFutureStatusPending) {
  Wait(100);
  printf("Signing in...\n");
}

// Print sign in results.
const firebase::auth::AuthError error =
    static_cast<firebase::auth::AuthError>(sign_in_future.error());
if (error != firebase::auth::kAuthErrorNone) {
  printf("Sign in failed with error `%s`\n",
         sign_in_future.error_message());
} else {
  firebase::auth::User* user = *sign_in_future.result();
  printf("Signed in as %s user.\n",
         user->Anonymous() ? "an anonymous" : "a non-anonymous");
}

Constructors and Destructors

~Auth()

Public functions

AddAuthStateListener(AuthStateListener *listener)
void
Registers a listener to changes in the authentication state.
CreateUserWithEmailAndPassword(const char *email, const char *password)
Future< User * >
Creates, and on success, logs in a user with the given email address and password.
CreateUserWithEmailAndPasswordLastResult() const
Future< User * >
Get results of the most recent call to CreateUserWithEmailAndPassword.
CurrentUser()
FIREBASE_DEPRECATED User *
Deprecated. Renamed to current_user().
Synchronously gets the cached current user, or nullptr if there is none.
FetchProvidersForEmail(const char *email)
Asynchronously requests the IDPs (identity providers) that can be used for the given email address.
FetchProvidersForEmailLastResult() const
Get results of the most recent call to FetchProvidersForEmail.
GetApp()
FIREBASE_DEPRECATED App &
Deprecated. Renamed to app().
Gets the App this auth object is connected to.
RemoveAuthStateListener(AuthStateListener *listener)
void
Unregisters a listener to authentication changes.
SendPasswordResetEmail(const char *email)
Future< void >
Initiates a password reset for the given email address.
SendPasswordResetEmailLastResult() const
Future< void >
Get results of the most recent call to SendPasswordResetEmail.
SignInAnonymously()
Future< User * >
Asynchronously creates and becomes an anonymous user.
SignInAnonymouslyLastResult() const
Future< User * >
Get results of the most recent call to SignInAnonymously.
SignInWithCredential(const Credential & credential)
Future< User * >
Asynchronously logs into Firebase with the given credentials.
SignInWithCredentialLastResult() const
Future< User * >
Get results of the most recent call to SignInWithCredential.
SignInWithCustomToken(const char *token)
Future< User * >
Asynchronously logs into Firebase with the given Auth token.
SignInWithCustomTokenLastResult() const
Future< User * >
Get results of the most recent call to SignInWithCustomToken.
SignInWithEmailAndPassword(const char *email, const char *password)
Future< User * >
Signs in using provided email address and password.
SignInWithEmailAndPasswordLastResult() const
Future< User * >
Get results of the most recent call to SignInWithEmailAndPassword.
SignOut()
void
Removes any existing authentication credentials from this client.
app()
App &
Gets the App this auth object is connected to.
current_user()
User *
Synchronously gets the cached current user, or nullptr if there is none.

Public static functions

GetAuth(App *app, InitResult *init_result_out)
Auth *
Returns the Auth object for an App.

Structs

firebase::auth::Auth::FetchProvidersResult

Results of calls FetchProvidersForEmail.

Public functions

AddAuthStateListener

void AddAuthStateListener(
  AuthStateListener *listener
)

Registers a listener to changes in the authentication state.

There can be more than one listener registered at the same time. The listeners are called asynchronously, possibly on a different thread.

Authentication state changes are:

  • When a user signs in
  • When the current user signs out
  • When the current user changes
  • When there is a change in the current user's token

It is a recommended practice to always listen to sign-out events, as you may want to prompt the user to sign in again and maybe restrict the information or actions they have access to.

Use RemoveAuthStateListener to unregister a listener.

Note:The caller owns listener and is responsible for destroying it. When listener is destroyed, or when Auth is destroyed, RemoveAuthStateListener is called automatically.

CreateUserWithEmailAndPassword

Future< User * > CreateUserWithEmailAndPassword(
  const char *email,
  const char *password
)

Creates, and on success, logs in a user with the given email address and password.

An error is returned when account creation is unsuccessful (due to another existing account, invalid password, etc.).

CreateUserWithEmailAndPasswordLastResult

Future< User * > CreateUserWithEmailAndPasswordLastResult() const 

Get results of the most recent call to CreateUserWithEmailAndPassword.

CurrentUser

FIREBASE_DEPRECATED User * CurrentUser()

Synchronously gets the cached current user, or nullptr if there is none.

Deprecated. Renamed to current_user().

FetchProvidersForEmail

Future< FetchProvidersResult > FetchProvidersForEmail(
  const char *email
)

Asynchronously requests the IDPs (identity providers) that can be used for the given email address.

Useful for an "identifier-first" login flow.

The following sample code illustrates a possible login screen that allows the user to pick an identity provider.

// This function is called every frame to display the login screen.
// Returns the identity provider name, or "" if none selected.
const char* DisplayIdentityProviders(firebase::auth::Auth& auth,
                                     const char* email) {
  // Get results of most recent call to FetchProvidersForEmail().
  firebase::Future future =
      auth.FetchProvidersForEmailLastResult();
  const firebase::auth::Auth::FetchProvidersResult* result =
      future.result();

  // Header.
  ShowTextBox("Sign in %s", email);

  // Fetch providers from the server if we need to.
  const bool refetch =
      future.status() == firebase::kFutureStatusInvalid ||
      (result != nullptr && strcmp(email, result->email.c_str()) != 0);
  if (refetch) {
    auth.FetchProvidersForEmail(email);
  }

  // Show a waiting icon if we're waiting for the asynchronous call to
  // complete.
  if (future.status() != firebase::kFutureStatusComplete) {
    ShowImage("waiting icon");
    return "";
  }

  // Show error code if the call failed.
  if (future.error() != firebase::auth::kAuthErrorNone) {
    ShowTextBox("Error fetching providers: %s", future.error_message());
  }

  // Show a button for each provider available to this email.
  // Return the provider for the button that's pressed.
  for (size_t i = 0; i < result->providers.size(); ++i) {
    const bool selected = ShowTextButton(result->providers[i].c_str());
    if (selected) return result->providers[i].c_str();
  }
  return "";
}

FetchProvidersForEmailLastResult

Future< FetchProvidersResult > FetchProvidersForEmailLastResult() const 

Get results of the most recent call to FetchProvidersForEmail.

GetApp

FIREBASE_DEPRECATED App & GetApp()

Gets the App this auth object is connected to.

Deprecated. Renamed to app().

RemoveAuthStateListener

void RemoveAuthStateListener(
  AuthStateListener *listener
)

Unregisters a listener to authentication changes.

Listener must previously been added with AddAuthStateListener.

Note that listeners unregister themselves automatically when they are destroyed, and the Auth class unregisters its listeners when the Auth class itself is destroyed, so this function does not normally need to be called explicitly.

SendPasswordResetEmail

Future< void > SendPasswordResetEmail(
  const char *email
)

Initiates a password reset for the given email address.

If the email address is not registered, then the returned task has a status of IsFaulted.

The following sample code illustrating a possible password reset flow. Like in the Anonymous Sign-In example above, the ResetPasswordScreen() function is called once per frame (say 30 times per second).

No state is persisted by the caller in this example. The state of the most recent calls are instead accessed through calls to functions like auth.SendPasswordResetEmailLastResult().

const char* ImageNameForStatus(const firebase::FutureBase& future) {
  assert(future.status() != firebase::kFutureStatusInvalid);
  return future.status() == firebase::kFutureStatusPending
             ? "waiting icon"
             : future.error() == firebase::auth::kAuthErrorNone
                  ? "checkmark icon"
                  : "x mark icon";
}

// This function is called once per frame.
void ResetPasswordScreen(firebase::auth::Auth& auth) {
  // Gather email address.
  // ShowInputBox() returns a value when `enter` is pressed.
  const std::string email = ShowInputBox("Enter e-mail");
  if (email != "") {
    auth.SendPasswordResetEmail(email.c_str());
  }

  // Show checkmark, X-mark, or waiting icon beside the
  // email input box, to indicate if email has been sent.
  firebase::Future send_future =
      auth.SendPasswordResetEmailLastResult();
  ShowImage(ImageNameForStatus(send_future));

  // Display error message if the e-mail could not be sent.
  if (send_future.status() == firebase::kFutureStatusComplete &&
      send_future.error() != firebase::auth::kAuthErrorNone) {
    ShowTextBox(send_future.error_message());
  }
}

SendPasswordResetEmailLastResult

Future< void > SendPasswordResetEmailLastResult() const 

Get results of the most recent call to SendPasswordResetEmail.

SignInAnonymously

Future< User * > SignInAnonymously()

Asynchronously creates and becomes an anonymous user.

If there is already an anonymous user signed in, that user will be returned instead. If there is any other existing user, that user will be signed out.

The following sample code illustrates the sign-in flow that might be used by a game or some other program with a regular (for example, 30Hz) update loop.

The sample calls SignIn() every frame. We don’t maintain our own Futures but instead call SignInAnonymouslyLastResult() to get the Future of our most recent call.

// Try to ensure that we get logged in.
// This function is called every frame.
bool SignIn(firebase::auth::Auth& auth) {
  // Grab the result of the latest sign-in attempt.
  firebase::Future future =
      auth.SignInAnonymouslyLastResult();

  // If we're in a state where we can try to sign in, do so.
  if (future.status() == firebase::kFutureStatusInvalid ||
      (future.status() == firebase::kFutureStatusComplete &&
       future.error() != firebase::auth::kAuthErrorNone)) {
    auth.SignInAnonymously();
  }

  // We're signed in if the most recent result was successful.
  return future.status() == firebase::kFutureStatusComplete &&
         future.error() == firebase::auth::kAuthErrorNone;
}

SignInAnonymouslyLastResult

Future< User * > SignInAnonymouslyLastResult() const 

Get results of the most recent call to SignInAnonymously.

SignInWithCredential

Future< User * > SignInWithCredential(
  const Credential & credential
)

Asynchronously logs into Firebase with the given credentials.

For example, a Facebook login access token, a Twitter token/token-secret pair).

An error is returned if the token is invalid, expired, or otherwise not accepted by the server.

SignInWithCredentialLastResult

Future< User * > SignInWithCredentialLastResult() const 

Get results of the most recent call to SignInWithCredential.

SignInWithCustomToken

Future< User * > SignInWithCustomToken(
  const char *token
)

Asynchronously logs into Firebase with the given Auth token.

An error is returned, if the token is invalid, expired or otherwise not accepted by the server.

SignInWithCustomTokenLastResult

Future< User * > SignInWithCustomTokenLastResult() const 

Get results of the most recent call to SignInWithCustomToken.

SignInWithEmailAndPassword

Future< User * > SignInWithEmailAndPassword(
  const char *email,
  const char *password
)

Signs in using provided email address and password.

An error is returned if the password is wrong or otherwise not accepted by the server.

SignInWithEmailAndPasswordLastResult

Future< User * > SignInWithEmailAndPasswordLastResult() const 

Get results of the most recent call to SignInWithEmailAndPassword.

SignOut

void SignOut()

Removes any existing authentication credentials from this client.

This function always succeeds.

app

App & app()

Gets the App this auth object is connected to.

current_user

User * current_user()

Synchronously gets the cached current user, or nullptr if there is none.

~Auth

 ~Auth()

Public static functions

GetAuth

Auth * GetAuth(
  App *app,
  InitResult *init_result_out
)

Returns the Auth object for an App.

Creates the Auth if required.

To get the Auth object for the default app, use, GetAuth(GetDefaultFirebaseApp());

If the library Auth fails to initialize, init_result_out will be written with the result status (if a pointer is given).

Details
Parameters
app
The App to use for the Auth object.
init_result_out
Optional: If provided, write the init result here. Will be set to kInitResultSuccess if initialization succeeded, or kInitResultFailedMissingDependency on Android if Google Play services is not available on the current device.

Send feedback about...

Need help? Visit our support page.