how do i restrict pages in ionic and firebase-authentication

52 Views Asked by At

As far as I can tell what I'm after is pretty basic, but I can't seem to find a clear solution to it, at least in the way I've built it up so far. I'm now completely stumped.

I've got the firebase email/password login working perfectly and redirecting to a registrants page. However I obviously want some safeguard in the registrants page to say 'If I'm not logged in, go back to the login page'.

In my authentication-service.ts I've set up a property of the class authService called isLoggedIn that just returns a true/false:

get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    console.log('user: ' + user);
    return (user !== null ) ? true : false;
  }

So I presumed (wrongly) that I could put the following in the ngOnInit() in the registrants page after the user is logged in, just so it'll fire up a check if the user is logged in once the page is visited, I can enter the redirectByUrl once I know it's working:

console.log('loggedin: ' + this.authService.isLoggedIn);

But I've learned that ngOnInit is only ever called once. So you could go into the page, then logout, then go back and it won't check if the user is logged in.

It works when i refresh the page, but not when it visits it within links. Is there a certain lifecycle hook that will check every time someone clicks on the link to visit the page or is it done a much simpler way?

I've realised I can put it in a ngDoCheck() but that seems a little excessive doesn't it?

1

There are 1 best solutions below

0
Nicho On

have you tried using ionViewWillEnter?

https://ionicframework.com/docs/angular/lifecycle