-1

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.

irkoch
  • 75
  • 9
  • So do you want to authenticate on reload or as a one off ? – Zze Jan 29 '19 at 09:12
  • It is false because you change it to true only at signIn time. What you could do is subscribe to some observable which will notify you whenever authentication state change. – Buczkowski Jan 29 '19 at 09:22
  • @Buczkowski yes I change it to true only at signin time, so why it's changing to false every time I refresh the page, if i'm wrong please can you explain to me. – irkoch Jan 29 '19 at 09:59
  • @Zz i want to stay logged in even though reload the page. – irkoch Jan 29 '19 at 10:02
  • 1
    @ChokriAbdo maybe this will help you - https://firebase.google.com/docs/auth/web/manage-users. Some question came to my mind: Why you don't use @angular/fire package? – Buczkowski Jan 29 '19 at 11:31
  • @Buczkowski, what I don't understand is what's wrong with this logic that I'm used, I know how to work with @angular/fire and may be will resolve the issue but why this doesn't work. refresh page --> authenticated = false ? – irkoch Jan 29 '19 at 11:40
  • @ChokriAbdo If you are signed in successfully some data is added to local storage or somewhere else (you can check it) and if you refresh the page you don't need to sign in again because you already have that data which could be used to automatically sign you in. – Buczkowski Jan 29 '19 at 11:52

1 Answers1

0

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807