0

i am building a Dashboard using Angular. The users of the dashboard are 1: Administrator (who is allowed to see the complete menu in sidebar) and 2: employee (who are only allowed to see part of that menu in the sidebar).

How should i define the menu items, so that they can be displayed dynamically based of the defined user permissions?

Thanks

  • 3
    👋👋 can you share some of your code ? – malbarmawi Jun 12 at 13:03
  • The first thing that came to mind is AuthGuards (see angular.io/guide/router#the-sample-application) – John Jun 12 at 13:16
  • If you have roles on your users, you can hide/show content that is relevant to the permission level. – John Jun 12 at 13:24
0
import { Directive, ElementRef, Input, OnChanges } from '@angular/core';
import { PermissionService } from '../services/web-api/permission.service';

@Directive({
  selector: '[appAuthorizeAction]'
})
export class AuthorizeActionDirective implements OnChanges {
  @Input('path') path: string;
  @Input('permission') permission: string;

  constructor(private el: ElementRef, private permissionService: PermissionService) {
  }

  ngOnChanges() {
    const authResult = this.permissionService.isAuthorized(this.path, this.permission);
    if (authResult !== true) {
      this.el.nativeElement.remove();
    }
  }
}

You can use the following and implement on any item: Example usage:

<button mat-button appAuthorizeAction [path]="'ADMIN_PANEL'" [permission]="'EXECUTE'">Click me!</button>

In case the user is authorized to perform the execute action, it will keep the button, else it will remove it.

0

Here is a snippet from my role-guard:

public canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<boolean> {
    const roles: UserRoles[] = route.data['roles'];
    return this.authenticationService.currentPrincipal.pipe(take(1), map((user) => {
        // console.log(roles);
        return roles.every((val) => user.roles.includes(val));
    }));
}

So you can see that my user authentication gets and sets the currentUser's roles.

When a user is created, their Principle roles are set as to what type of user they are. (they could be updated by admin)

Let me know if you need more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.