Send data to angular guardians

Asked

Viewed 47 times

0

I need to make a Guard to check if a user has permission the system screens.

I have an array saved in localstorage that informs me the permissions of a user.

Example: [1,2,5], where the number is the screen id that the person can access.

I wonder if there’s any way I’m sending data from my route file to the guardian.

Something like:

{ path: 'custofixo', component: CustofixoComponent, data:{idtela: 1}, canActivate:[PermissoesTelaGuard], pathMatch: 'full' }

There’s a way to retrieve this idol from my guardian?

  • You can enter the router or activatedRoute in your Uard constructor and take the information there.

  • I didn’t want to be boring, but localstorage is not a cool way to do this, anyone can open developer tools and add numbers to the permissions array easily. The most correct and traditional way is to have a back-end service taking care of these permissions and you get into Authguard with an array that came from there. Then, that’s easy, just check on canLoad() or canActivate() if the array has the screen id you are accessing

1 answer

0

You can use a service that explicitly provides Toke or permissions.

user.service.ts

...
getPermissions(){
   const currentUser = localStorage.getItem(currentUser);
   return currentUser.permissions; // Aqui você retorna o array com suas permissões
}
...

app.guard.ts

 constructor(private userService: UserService) { }

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const idTela = route.snapshot.data['idtela'];
    const permissions = this.userService.getPermissions();
    if (!permissions.includes(idTela)) {
      alert('Activation blocked');
      return false;
    }
    return true;
  }

I believe that solves.

Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.