firebase.auth().currentUser is null after refresh

#1

I thought the firebase javascript SDK was meant to automatically refresh the token and keep the user logged in. When I refresh my page (web) the currentUser is reset to null and my authguard fails and I have to log in again.

Basically I want it to auto login the user / refresh token if needed. Anyone know how to do this?

Looked at these but couldn’t figure it out:


#2

Hello, You can do something like this

Import AngularFireAuth in your page.ts file

import { AngularFireAuth } from 'angularfire2/auth';

After add this

constructor(public fAuth: AngularFireAuth) {
	var user = this.fAuth.auth.currentUser;
	
	if (user != null) {
		  -----your code---
	}
}

And also your can set/add Session

Open app.component.ts file add this

import { AngularFireAuth } from 'angularfire2/auth';
constructor(public fAuth: AngularFireAuth) {
platform.ready().then(() => {

this.fAuth.authState
        .subscribe(
          user => {
            if (user) {
              this.rootPage = HomePage;
            } else {
              this.rootPage = IntroPage;
            }
          },
          () => {
            this.rootPage = IntroPage;
          }
        );
}
}

Hope it help you :slight_smile:

#3

Thanks gokujy but I am not using the AngularFire package.

I solved it by putting this in my auth guard.
This was a useful tutorial: https://javebratt.com/ionic-firebase-tutorial-auth/

export class AuthGuard implements CanLoad {

  constructor(private authService: AuthService,
              private router: Router) {}

  canLoad(
    route: Route,
    segments: UrlSegment[]
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged((user: firebase.User) => {
        if (user) {
          console.log('User is logged in');
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigateByUrl('/auth');
          resolve(false);
        }
      });
    });
  }
1 Like