angularfire2 - firestore: Missing or insufficient permissions on logout
Version info
Angular: 4.4.4
Firebase: 4.8.2
AngularFire: ^5.0.0-rc.4
Other (e.g. Ionic/Cordova, Node, browser, operating system): browser, macbook
How to reproduce these conditions
I had the same issue for weeks which was written in StackOverflow: https://stackoverflow.com/questions/46831468/ionic2-angularfire2-firestore-missing-or-insufficient-permissions-on-logout
Maybe i forget to clean up cache or remove something?
Could someone please help me out? Thanks in advance!
Yes,
Normally this is solved by doing an unsubscribe of your subscription in the ngOnDestroy(). That's the way I do it.
However, it is very difficult to pinpoint which you should unsubscribe as the error does not give any indication on that. It would be nice that the error points you in the right direction, for example the path which was not unsubscribed or the last path segment. Anything.
Your solution works for me. Thanks a lot!
It would be nice that the error points you in the right direction, for example the path which was not unsubscribed or the last path segment. Anything.
@LanderBeeuwsaert You were right. It would save me a lot of time to have this info.
I solved this issue using this StackOverflow post: https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription
In my app, I kept getting this error, and it turned out that I missed unsubscribing from a subscription to the snapshotChanges() Observable reading from my firestore database.
TL;DR
- Define variable
ngUnsubscribe: Subject<void> = new Subject(); - Call
.takeUntil(this.ngUnsubscribe)before each.subscribe()call - Call
this.ngUnsubscribe.next();followed bythis.ngUnsubscribe.complete();inngOnDestroy()
Example:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
import { MyThingService } from '../my-thing.service';
@Component({
selector: 'my-thing',
templateUrl: './my-thing.component.html'
})
export class MyThingComponent implements OnDestroy, OnInit {
private ngUnsubscribe: Subject<void> = new Subject();
constructor(private myThingService: MyThingService) { }
ngOnInit() {
this.myThingService.getThings()
.takeUntil(this.ngUnsubscribe)
.subscribe(things => console.log(things));
this.myThingService.getOtherThings()
.takeUntil(this.ngUnsubscribe)
.subscribe(more_things => console.log(more_things));
}
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
Calling .takeUntil(this.ngUnsubscribe) before each of our .subscribe() calls will guarantee that all subscriptions will be cleaned up when the component is destroyed.
I'm having this problem too, but I subscribe to data in my services, so unsubscribing upon component destruction is not enough, neither listening for changes in the authState apparently, because these errors happen before the onAuthStateChanged is triggered, so making a switchMap on that doesn't help.
Can someone help me with that?
I'm also using services (and ngrx effects), doing that seems to be working:
getActivities(): Observable<DocumentChangeAction[]> {
return this.firestore
.collection(this.path, ref => ref.where('authorId', '==', this.fireAuth.auth.currentUser.uid))
.stateChanges()
.pipe(takeUntil(this.fireAuth.authState.filter(u => !u)));
}
Hi, @YeFFreY, thanks for the response. I saw this approach somewhere but didn't give too much attention because making switchMap and checking for a null value in the authState seemed to make so much sense that I didn't give this a chance. I'll try it tomorrow.
@YeFFreY This approach doesn't work for me. I've used it in every assignment of the Observable and I still have the same amount of errors regarding permission. The only way to fix them seems to be removing the reference (not a solution). The workaround I'm using for the moment is to route the user back using window.location. Thanks for the help.
hi @rwmb I'm stuck in this problem a week ago . what did you do for this problem . please explain with code if possible :)
@MoradAbdelgaber I didn't find a way to refresh the database subscribers, because I access the data from the templates as well, so even by saving the subscriptions and unsubscribing on logout, the template ones don't refresh. The only solution I could find was to refresh the whole application after logout (a bad workaround), using window.location.href = '/'
@rwmb is there any problem to console log this error ? is that affect the performance of the application ?
I'd suggest leaning on rxjs and using a takeWhile afAuth.authState not null
@jamesdaniels In this case that wouldn't work. All active snapshot listeners will throw the error immediately on logout(), irregardless of takeWhile.
It's surprisingly hard issue to tackle.
Here's what I did to solve this problem: I wrapped the authState in a BehaviourSubject (it's possible to use a ReplaySubject as well, or a simple Subject I guess) like this:
this.afAuth
.authState
.subscribe((data) => {
if (!this.$logged) {
this.$logged = new BehaviorSubject<any>(data);
this.user.initialize(this.$logged);
} else {
this.$logged.next(data);
}
});
and to fix the problem I use this $logged subject instead, because I can easily send null from this one upon sign out.
signOut() {
this.afAuth
.auth
.signOut()
.then(() => {
console.log('signout');
this.$logged.next(null);
this.router.navigate(['/']);
});
}
I know there's a better way to implement this, maybe extending the afAuth and using our own auth handler, but since I wanted to control the user initialization I did it this way. I appreciate suggestions on improvements and hope this helps. @larssn @MoradAbdelgaber
Having the same issue w/ my user init, can't figure out how to prevent or catch the error on logout:
this.user = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
return this.afs.doc<IUser>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
}),
tap(user => localStorage.setItem('user', JSON.stringify(user))),
shareReplay(1), // Cache me
startWith(JSON.parse(localStorage.getItem('user')))
);
Update: This code was not the cause of the issue. I had accidentally set up a subscription in a buried service that wasn't being unsubscribed from. I pulled the sub out of that service and set it up for components to sub to... and no more permissions issue on logout.
If you have a large app, try killing all services + components (accept your auth) + routes first to make sure it's not a rouge subscription like it was for me 👍
Really looking forward to more detailed Firebase error/debug console output for stuff like this...
I had a very similar issue and was able to solve it with the help of @stanleyeosakul's solution. I added a takeUntil() operator which includes the Subject that I used to emit to unsubscribe from the authState in my logout function (see below).
The subject property:
private ngUnsubscribe$: Subject<void> = new Subject();
The subscription that caused problems and where I added the takeUntil() before subscribing:
this.auth.afAuth.authState
.takeUntil(this.ngUnsubscribe$)
.subscribe(
user => {
if (user) {
this.rootPage = HomePage;
this.getUser = this.db
.collection("users", ref =>
ref.where("email", "==", user.email)
)
.valueChanges();
} else {
this.rootPage = LoginPage;
}
}
);
The logout function that emits a value before it signs out:
public logout(): void {
this.ngUnsubscribe$.next();
this.ngUnsubscribe$.complete();
this.auth.signOut();
this.nav.setRoot(LoginPage);
}
I am having same issue at signout mainly because ngOnDestroy is asynchronous. And in the tabbed approach, components are not getting destroyed. And I never subscribe manually. All subscriptions are happening with async calls in the template. For now we removed logout functionality and added switch user to take the user back to login page with out logging out. Not sure what this does but the functionality works fine without these errors anymore.
I am also planning to try navigating to login page and use settimeout for logout with delayed logout.
Are there any official recommendations regarding this issue? Thanks
I'm also using services (and ngrx effects), doing that seems to be working:
getActivities(): Observable<DocumentChangeAction[]> { return this.firestore .collection(this.path, ref => ref.where('authorId', '==', this.fireAuth.auth.currentUser.uid)) .stateChanges() .pipe(takeUntil(this.fireAuth.authState.filter(u => !u))); }
After spending literally days trying to figure this out, your solution is the only one that would work for me. My question though: why is this necessary on the valuechanges? My application successfully unsubscribes on destroy, and yet valuechanges is the only way to fix this issue. Makes you wonder if there's still a memory leak somewhere (is it still listening even after I've unsubscribed?).