I am trying to prevent regular users from accessing the admin side of my app. Currently, the admin property on the Firestore document is either true or false. If false, they should be redirected to the home page when trying to access it, otherwise allow the user to continue to the page.
Here is my admin-auth-guard.service.ts
userDoc: AngularFirestoreDocument<User>;
user: Observable<User>;
constructor(private afAuth: AngularFireAuth,
private afs: AngularFirestore,
private router: Router) {}
canActivate() {
this.userDoc = this.afs.doc('users/' + this.afAuth.auth.currentUser.uid);
this.user = this.userDoc.valueChanges();
return this.user.map(role => {
if (role.admin)
return true
this.router.navigate(['/']);
return false;
});
}
I believe the code will work, though when initializing the Admin Auth Guard, the request happens too fast and uid is null.
I receive this error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'uid' of null
TypeError: Cannot read property 'uid' of null
Firestore and angular seems to be a niche topic, not much information on both together. Any help would be appreciated!