0

the user's permissions come in an array, as I do to validate whether or not he has access by iterating the arrat

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 

   const expectedPermission = route.data.expectedPermission;
   const token= localStorage.getItem("Token")
   const tokenPayload = decode(token);
   const role=tokenPayload['https://menu-api.demo.com/roles'][0];
   console.log(route);
   const permissions=["create:user", "delete:user", "read:user"]
     if (!this.auth.isAuthenticated() || permissions !== expectedPermission) {
       this.router.navigate(['external-api']);
         return false;
     }

   return true;
 }

{
    path: 'profile',
    component: ProfileComponent,
    canActivate: [RoleGuard], 
    data: { 
      expectedPermission: 'read:user'
    }
  }
Jorge Nava
  • 495
  • 1
  • 5
  • 10

2 Answers2

1

You need to see if the expectedPermission exists in the permissions array.

There are several ways of doing this. If the strings are guaranteed to be exact matches (the same case), then you can use the includes array function.

if (!this.auth.isAuthenticated() || !permissions.includes(expectedPermission)) {
  // user doesn't have permission
}
Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
0

Your problem is that you are comparing the references of the arrays, which is probably not what you want.

You should check if all of the expectedPermissions exists in permissions. This can be accomplished by combining every and includes function:

if (!this.auth.isAuthenticated() || !expectedPermission.every(expectedPermission => permissions.includes(expectedPermission))) {
 //no permission
}

Every loops over the expectedPermissions array and only returns true if the given predicate is true for every item. The predicate we use is to check if the item is included in the permissions array.

Max K
  • 1,062
  • 9
  • 11