sir-haver
sir-haver

Reputation: 3602

Firebase authentication with localId / idToken (instead of email / password)

In my app, when a user logs in, I use firebase.auth to authenticate the user based on the email/password the user typed:

firebase.auth().signInWithEmailAndPassword(userInputs.email.value, userInputs.password.value)

Then I dispatch it to the redux state and also set the received localId and idToken on the local storage:

localStorage.setItem('token', response.user.qa);
localStorage.setItem('localId', response.user.uid);

When the user closes the app window and then reopen the app later, the localId and idToken are still set in the localstorage, but to re-authenticate I need to supply email and password. Is it possible to authenticate with localId/idToken, or should I save the email/password on localStorage instead of saving the two tokens?

Upon checking if the user is authenticated:

var user = firebase.auth().currentUser;
console.log(user);

I get 'null'. It seems that I must sign in even if I already have the localId, without signing in I don't have access to the database.

Also, obviously my database rules grant access to the db only to authenticated users:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Thanks in advance!

Upvotes: 2

Views: 3178

Answers (1)

Shota Tamura
Shota Tamura

Reputation: 301

You don't have to store the email & password in the localstorage. Firebase library automatically retain the auth infomation locally.

The cause of you get null is you are trying to get user info with Synchronous code. Which means that you are trying to get user before the firebase library's initalization.

firebase.auth().currentUser; // <= synchronous

Following code runs Asynchronously and you can get user after the firebase library initalize.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

Upvotes: 2

Related Questions