How can we approach to have role based authentication to some of the functionalities of angular app?

Viewed 15

I am trying to provide role based access to certain functionalities in the app. For example, we have Delete functionality option, so that delete option should only be visible to certain level of roles (users) and should only have read-only access, While for some can delete it as well. Is such approach possible? The application already provides access using identity management. Just wanted to know can this be possible role based, or may be we can access the database of the idm. Any idea of how this can be implemented are welcome.

1 Answers

Yes it is possible. What you can do is define an auth service. If you use NgRx, the below solution could what you want. In this service keep for example currentRole$ as below:

auth.service.ts

import { Injectable } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { selectUser } from './store/selectors';
import { selectIsLoggedIn } from './store/selectors';

export enum ROLES 
  customer = 'client',
  manager = 'manager',
  admin = 'admin'
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  private currentRole$: Observable<ROLES>;
  private isLoggedIn$: Observable<boolean>;

constructor(private store: Store) {
    this.currentRole$ = this.store.pipe(
      select(selectUser),
      filter((user) => !!user),
      map((user) => user.role)
    );


    this.isLoggedIn$ = this.store.pipe(select(selectIsLoggedIn));

   }

 getCurrentRole(): Observable<ROLES> {
    return this.currentRole$;
  }

  isLoggedIn(): Observable<boolean> {
    return this.isLoggedIn$;
  }
   
} 

You can get subscribe the current role in your component. Based on the currentRole you can decide whether you can show the UI to the user.

app.component.html

<button *ngIf="(currentRole$ | async) === ROLES.client (click)="onMenuClick()"> Client Button </button>
Related