Refresh page get log out automatically in angular

2019-09-21 10:33发布

问题:

I'm using firebase for the signIn and signup. that is my authService look like :

token: string;
authenticated: boolean = false;
signinUser(email: string, password: string) {
        firebase
            .auth()
            .signInWithEmailAndPassword(email, password)
            .then(response => {
                this.authenticated = true;
                console.log('authService-->signinUser-->authenticated', this.authenticated);


                //Set the a wallet using a combination of the email and the name of the network e.g. Majd@gmail.com@stschain
                this.dataService.setWallet(`${email}${this.domainExtenstion}`);
                this.setEmail(email);
                this.router.navigate(['/dashboard']);
                console.log('sinign in')
                firebase
                    .auth()
                    .currentUser.getIdToken()
                    .then(
                        (token: string) => {
                            (this.token = token);
                            // localStorage.setItem('token', JSON.stringify(token));
                        }
                    );
            })
            .catch(error => {
                console.log(error);
                alert(error);
            });

    }

isAuthenticated() {
   return this.token != null;       
}

and in my authGuardService im calling canactivate methode like this :

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (!this.authService.authenticated) {
      console.log('cant load' )
      this.router.navigate(['/signin']);
    }
    console.log('can load' )
    return this.authService.isAuthenticated();
  }
}

but when i refresh the page this authenticated value get false always.

Please, anyone, know the cause that will appreciate.

回答1:

In your code you do:

firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then(response => {
        this.authenticated = true;

This then block only runs when the user explicitly signs in. It does not automatically run when the page gets reloaded.

But Firebase Authentication does automatically (try to) restore the user's sign-in session when the page is reloaded, your code just isn't aware of it. To detect auth state changes, use an auth state listener (as shown in the documentation):

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

Note that the onAuthStateChanged callback gets called for both explicit (e.g. you calling signInWith...) and implicit (e.g. page reload) auth state changes, so consider moving (some of) your code from the then() block to this callback.