Angular 6 Role based Authentication

99封情书 提交于 2019-12-04 22:55:40

You can create different component and render the component conditionally. Consider your example. For that I create 2 component 1. view component 2. Create component.

like consider the codes

<div>
   <button *ngIf="usertype!=='employeee">Delete</button> <!--show delete button if user is not employee-->
   <create *ngIf="usertype!=='employeee"></create> <!-- Show create component if usertype is not emplyee -->
   <view [data]="data"></view> <!-- view for all type of user-->
</div>

Any way you are going to give specific button for create, update, delete and view after creating button you are going to enable or disable button programmatically correct .If this is your need means follow the below steps

create button with [disabled] option for ex.,

<button text="click" [disabled]="isAuthorised">Create</button>

<button text="click" [disabled]="isAuthorised">Delete</button>

Here isAuthorised is the variable which is in typescript make the variable as boolean(true / false) based on user role.it will enable or disable button accordingly

There are so many different approaches you can follow but the basic idea behind restricting routes based on a certain condition by using route-guards.

in your case, you can have routes which load your modules lazily when route-guard authorize to use it and further nested routes loaded same way.

Decide your routes module.

{
   path:'/dashboard',
   loadChildren: './lazy.module#LazyModule'
   canActivate:[ModuleRouteGuard],
   data: {
      accessRoles: ['Manager','HR']
   }
}

LazyModule_Routes.ts

{
   path:'/board',
   component: ManagerBoard
   canActivate:[ChildRouteGuard],
   data: {
      accessRoles: ['Manager']
   },
   resolve: {
      userRoles: 'userRolesResolver'  //use this resolver service to get data inside component so to decide if user can read/write . OR you can also use activatedRoutes data
   }
}

Route-Gaurd.ts

@Injectable()
class ModuleRouteGuard implements CanActivate { (1)
  constructor(private userService: UserService) {}; (2)

  canActivate() {
    console.log("OnlyLoggedInUsers");
    if (this.userService.isLoggedIn()) { (3)
      return true;
    } else {
      window.alert("You don't have permission to view this page"); (4)
      return false;
    }
  }
}

your app resolver which brings user roles from the server.

@Injectable()
class UserRolesResolver implements Resolve<Team> {
  constructor(private backend: Backend) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any>|Promise<any>|any {
    //return this.backend.fetchTeam(route.params.id);
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!