Gianluca
Gianluca

Reputation: 980

disable firebase Auth State Persistence

I have this login function currently:

AuthorizationHome.doSignInWithEmailAndPassword(email, password)
    .then(() => {
      firebase.auth().onAuthStateChanged((user) => {
                ..........

But it basically keeps my session logged in even when I close my browser, restart my computer, it does it all. Because the user is able to manage their payments from my app, I need to make sure that if they close the browser, it logs them out.

Firebase docs tells me to do it like this:

    firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(() => {
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

It is different then my original code, so I am not sure how to do this. I'm totally new to the way firebase works so I am a little confused.

Upvotes: 1

Views: 381

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38767

Are you trying to execute firebase.auth().onAuthStateChanged after AuthorizationHome.doSignInWithEmailAndPassword(email, password) successfully resolves?

firebase
  .auth()
  .setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(() => {
    return AuthorizationHome.signInWithEmailAndPassword(email, password).then(() => {
      firebase.auth().onAuthStateChanged((user) => { /* do things */ });
    });
  })
  .catch((error) => {
    // Handle Errors here.
    const errorCode = error.code;
    const errorMessage = error.message;
  });

That being said, you can probably run setPersistence(firebase.auth.Auth.Persistence.SESSION) as part of app initialization separately. It doesn't have to be run right before every execution of doSignInWithEmailAndPassword:

// app initialization
firebase
  .auth()
  .setPersistence(firebase.auth.Auth.Persistence.SESSION)

// somewhere else on demand
AuthorizationHome.doSignInWithEmailAndPassword(email, password)
    .then(() => {
      firebase.auth().onAuthStateChanged((user) => {

Hopefully that helps!

Upvotes: 1

Related Questions