1
votes

I want to be able know the role of my user at anytime throughout my app. So I have a /user/$uid/role node.

I want to be able to setup angular route guards to route different types of users to different areas of the app. Different roles should not be able to access the other. Think of a freelance/employer site. Only freelancers should be able to access the routes for freelancers.

I have it working where once a user logs in, I query the node where the $uid equals the user from the auth.subscribe. I've tried setting up a behavior subject where I'm observing a AuthInfo instance. Whoever I refresh the page, requeries the firebase auth state, runs the query to check the role again. This is too slow and the router guard prevents access since it thinks the user has no role.

How can I persist and monitor the user and their role throughout the app? Do I need to use ngrx or redux?

I imagine the object would look like

Auth: { $uid: uid, role: groupA}

I'm using angularfire2.

1

1 Answers

0
votes

You just need to have authguards for roles, and then pass them in canActivate array in router

for example. I have Admin and Judge role in my app. So I have judge guard:

import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService} from './auth.service';
import {tap, map, take} from 'rxjs/operators';

@Injectable()
export class JudgeGuard implements CanActivate {

  constructor(private auth: AuthService, public router: Router) {}

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

    return this.auth.user.pipe(
      take(1),
      map(user => !!(user && user.roles.judge)), // if user exists and has role -> true nor false
      tap(isJudge => {
        if (!isJudge) {
          console.log('Acces denied - Judges Only');
          this.router.navigate(['/']);
        }
      })
    );
  }
}

and then in router-module,

const routes: Routes = [
 ...
  {path: 'judge-dashboard', component: JudgeDashboardComponent, canActivate: [AuthGuard, JudgeGuard]},