0

I am using firebase with authentication and firestore. Authenticated users are stored in database upon signup with extra roles field where some user have 'admin' role. I want to protect the admin route and i use the canActivate route guard. In the canActivate function I use 2 observables. The first 1 gets the logged in user and nested in that another observable which gets the saved users from firestore, uses the imformation from there o cehck if the logged in user is admin or not. The problem is that the routeguard works fine when the browser refreshes after the route types in the broser but when the route is called with the routerlink on the button, nothing happens.

tried using sycnronous values but those work only once and stop working after navigating around.

The canActivate function: https://i.stack.imgur.com/ArlX2.png

canActivate(router: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return this.afAuth.getStateOnly().pipe(switchMap(user => { return this.db.getRole(user.uid) }))

  }

The observables used: https://i.stack.imgur.com/0pzgv.png https://i.stack.imgur.com/wN0iG.png

// user object or null from firebase

 getStateOnly() {
    return this.afAuth.authState 
  }

//checking the role and returning true or false(userArr is an array of users observable to store the users from firestore)

getRole(uid: string): Observable<boolean> {
    return this.userArr.pipe(map(users => {
      return users.filter(user => {
        if (user.uid === uid) {
          return user
        }
      })[0].roles.includes('admin')
    }))

So this works only when i type the path in the browser and the browser refreshes when loading the route. It is not working when i click the admin button to navigate to admin page (not with routerLink nor router.navigate(..))

Nándor Szűcs
  • 151
  • 1
  • 9

1 Answers1

0

image of new canActivate() I have managed to solve the problem but i am still not sure why the previous implementation did not work..firebase is wierd sometimes. So I made a new observable which gets the users from firestore and i was transforming that output directly in the can activate function, see image. Previously i got the users, transformed it and i called the transformed observable from the canactivate function wich did not seem to work. So it was something wrong with the data stream.

Nándor Szűcs
  • 151
  • 1
  • 9