Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore: Unsubscribe from valueChanges (user gets "Missing permissions" when signing out)

Is it possible to unsubscribe from a valueChanges() ? When my users sign in, I fetch their user data like this

this.user$ = this.afAuth.authState.flatMap(authUser => {
  if (!authUser) {
    this.user = null;
    return Observable.of(this.user);
  }

  return this.db.doc<UserServerData>(`users/${authUser.uid}`)
    .valueChanges()
    .map(user => new User(authUser.uid, user));
});

Of course I have a rule on Firestore saying that only the user with a specific id can read this user datas... So when a user signs out, every queries with a rule on the user id fail and I get a "Missing permissions" error.

So here's my question, how should I do this ? Is there a way to unsubscribe from a query ?

Thanks a lot

like image 532
Maslow Avatar asked Nov 22 '25 16:11

Maslow


1 Answers

AngularFire author here.

You have two options. Either return an empty set for logged out users or use a route guard.

Returning an empty set is easy. Replace .of(null) with an empty array.

this.user$ = this.afAuth.authState.switchMap(authUser => {
  if (!authUser) {
    this.user = null;
    return Observable.of(null);
  }
  return this.db.doc<UserServerData | null>(`users/${authUser.uid}`)
    .valueChanges()
    .map(user => new User(authUser.uid, user));
});

Using a route guard is a bit more complicated and requires a dependency on the @angular/router. However, it will ensure that the user exists before the route loads.

like image 177
David East Avatar answered Nov 24 '25 17:11

David East



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!