Currently, I am tackling a new project that involves Angular along with Firebase for Authentication and Firestore as the database. However, while implementing an Admin Guard to check user privileges, I encountered a perplexing issue where the guard condition does not seem to execute.
The function responsible for fetching user data from the database is as follows:
get(uid: string): AngularFirestoreDocument<User> {
return this.afs.doc(`users/${uid}`)
}
Within the Auth Service, the method to retrieve the user details is defined as:
get dbUser$(): Observable<any> {
return this.user$.pipe(
switchMap(user => {
if(user && user.uid) {
return this.dbService.get(user.uid).valueChanges();
} else {
return of(null);
}
}),
)
}
Furthermore, in the AdminAuthGuard class, the logic to determine admin access rights is implemented as described below:
export class AdminAuthGuard {
constructor(
private authService: AuthService,
private dbService: DatabaseService,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.dbUser$
.pipe(
map((userData: any) => {
console.log('Admin Auth Guard returns true');
if(userData && userData.isAdmin) {
return true;
} else {
console.log('Admin Auth Guard returns false');
return false;
}
})
);
}
}
Despite having debug statements placed strategically, the expected output is not being generated during runtime. The scenario becomes more puzzling when the expected 'isAdmin' property of the user object seems to appear after multiple iterations.
The routing configuration intended for paths requiring admin authentication are shown below:
{path: 'admin/products', component: AdminProductsComponent, canActivate: [AdminAuthGuard]},
{path: 'admin/orders', component: AdminOrdersComponent, canActivate: [AdminAuthGuard]},
In an attempt to troubleshoot, I created an Admin Guard for two separate routes but was unable to elicit any response from the functions invoked.