Tom
Tom

Reputation: 4033

How to check and store whether user is logged in correctly?

Is there a better way of checking whether a user is logged in? Because I use the following approach for multiple apps and serving them somehow causes disparities, since it confuses the current app's item with other app's items.

I check whether a user is logged in like this:

constructor(private afAuth: AngularFireAuth, private router: Router, private db: AngularFirestore) {
    this.userData = new ReplaySubject<UserDetails>();
    afAuth.auth.onAuthStateChanged(user => {
      if (user) {
        this.user = user;
        const local = localStorage.getItem('user');
        if (local !== null) {
          this.userData.next(JSON.parse(localStorage.getItem('user')));
        } else {
          this.fetchUserData();
        }
      } else {
        localStorage.setItem('user', null);
      }
  });
}

get isLoggedIn(): boolean {
    const user = localStorage.getItem('user');
    return user !== 'null';
}

Upvotes: 1

Views: 102

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598817

If each app is served from its own domain, then each will have its own localStorage and there can't be any conflict/confusion between them.

If you're serving multiple apps from the same domain, you'll have to use a unique name in the local storage for each app. Something like localStorage.setItem('app1_user', null) vs localStorage.setItem('app2_user', null).

But note that Firebase Authentication only has a single authenticated user per domain. So if you're serving multiple apps from the same domain, the user is (according to Firebase Authentication) signed in to all of them (or to none of them) at the same time.

Upvotes: 1

Related Questions