javascriptangularfirebaseauth-guard

CanActivate guard for multiple users in angular


I've got a working canActivate auth-guard like this:

    return this.auth.user$.map(user => {
      if (user) return true;

      this.router.navigate(["/login"], {queryParams: {returnUrl: state.url}});
      return false;

    });
  }

and use it for routes like this:

{path: 'my-project', component: ToolComponent, canActivate: [AuthGuard]}

i want to have multiple users be able to work on the same project

example: User A & B on project 1 User C & B on project 2 and so on

what's the best way to to this?

ty!


Solution

  • the "typical" is assing to each user a "role" (admin/user), but in your case I imagine you has severals projects. So your "user" should has a property with the project can access and the path of your router can add "data". Some like

      { path: 'project1/ComponentOne', component: Component1,
          canActivate: [CheckGuard],data:{project:"project1"} },
    

    Your "checkGuard can take account the "user" and also the "data"

    @Injectable()
    export class CheckGuard implements CanActivate {
      constructor(private router: Router,private accountService:AccountService) { }
      canActivate(activatedRouteSnapshot: ActivatedRouteSnapshot, 
         routerStateSnapshot: RouterStateSnapshot) {
    
        //in activatedRouteSnapshot.data you has the "data" of the router
        console.log(activatedRouteSnapshot.data)
    
        ...your logic here..
      } 
    }