Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 show/hide components/parts based on roles/claims

Tags:

angular

I am trying to understand best practices about security aspect of angular application. Lets say i have a view with details screen of the model. What i want to be able to do, based on roles/permissions for the given user (gotten from jwt claims, for example) is:

  1. enable/disable certain input fields based on the fact if user is/isn't of certain role so, effectively some roles can edit the record and some can't

  2. show/hide 'save' button again based on role, again to prevent certain roles from editing

i understand there is canActivate but if feels like on a component level and what i need is a bit more granular approach to change things within components based on roles.

what are the best practices?

like image 908
dee zg Avatar asked Oct 04 '16 09:10

dee zg


2 Answers

Use Ng2Permission module directives for show/hide or enable/disable element.

For example assume you already with PermissionService defined some permission among Admin, Reporte and etc. Now below example, delete button enabled when Admin permission defined or added to permission store. See this link: PermissionService

<button type="button" class="btn btn-danger btn-xs" 
  [hasPermission]="['Admin']"
  onAuthorizedPermission="enable"
  onUnauthorizedPermission="disable">
  <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
  Delete
</button>
like image 103
Javad Rasouli Avatar answered Nov 18 '22 11:11

Javad Rasouli


Lets assume you have a profile saved somewhere in an object.

{
  name: 'asdas',
  role: 1 // for example, 1 for normal user, 2 for admin
}
  1. enable/disable certain input fields based on the fact if user is/isn't of certain role so, effectively some roles can edit the record and some can't

you can add disabled based on his role

[disabled]="user.role === 1"
  1. show/hide 'save' button again based on role, again to prevent certain roles from editing

Same for this one

*ngIf="user.role === 2"

However, you want to double check these things in the backend if the user is actually an admin when editing fields f.e.

like image 28
koningdavid Avatar answered Nov 18 '22 10:11

koningdavid