1

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.

Gianluca
  • 900
  • 8
  • 27

1 Answers1

1

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!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • worked like a gem, I was able to use it on login, as that is best for this type of app in my opinion. I appreciate your detailed answer! – Gianluca Apr 30 '21 at 17:59