Dave
Dave

Reputation: 1775

How can you retrieve the UserCredential from onAuthStateChanged

My app supports multiple identity providers (google, facebook, email), because of this it has made it easier to trigger login flows by subscribing to callbacks from onAuthStateChanged. I'm trying to determine if it's the first time a user has logged in. This data appears to be available via this function getAdditionalUserInfo(userCredential: UserCredential). Otherwise I need to trigger this login flow from several different code paths and it will be asynchronous from the main login flow.

export const watchAuthChanges = (onLoginSuccess, onLogoutSuccess, onError) => {
  onAuthStateChanged(auth, async (user) => {
    if (user) {
      const token = await getIdToken(user);
      const refreshToken = async () => {
        return await getIdToken(user, true);
      }

      const additionalInfo = getAdditionalUserInfo(???)
      // I want to pass in the additional user info into onLoginSuccess
      onLoginSuccess(user, token, refreshToken);
    } else {
      onLogoutSuccess();
    }
  }, (error) => {
    onError(error)
  });
}

Upvotes: 2

Views: 295

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599601

The UserCredential is only available when the user actively signs in. There is no way to get it when the authentication state is restored otherwise.

But you can actually also determine whether this is the first time the user is signed in from looking at the metadata of the User object. If the creationTime and lastSignInTime values are the same (or really close to each other), it is the first time the user is signed in.

Upvotes: 2

Related Questions