2

In my Angular8 app, there are 2 dashboard pages for User and Admin and I want to load the corresponding dashboard by using the role of a user to the PanelComponent. I think to use ngIf in the PanelComponent.html and load the corresponding dashboard according to role, but not sure if this is a good idea or not :(

On the other hand, there are some questions about that like How to achieve Role Based redirection after login in Angular-5?, but there is not a good example about that. So, what is the best way to implement this approach?

  • After the `login` based on the role route to desired page. Also you can use `Guards` to control the access to the route. – Chaitanya Aug 05 '19 at 10:06

1 Answers1

4

Angular Route Guards is the best practise in order to support role based access. However if you want to support role based access for only two pages and the requirements will not expand in time then I do not see anything wrong with using ngIf. I would go that way in such a case.

If you want to use route guards anyway, then you should implement CanActivate interface accordingly. It is going to be your route guard implementation. This class is responsible of showing or not showing the requested page depending on the role. If the user does not have the required role then it redirects to a http 404 or 403 page you had created.

import { Injectable } from '@angular/core';
import { 
  Router,
  CanActivate,
  ActivatedRouteSnapshot
} from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class RouteGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {
  }
  canActivate(route: ActivatedRouteSnapshot): boolean {
    if (
      !this.auth.isAuthorized(route.data.roleCode)
    ) {
      this.router.navigate(NotFoundPage.PATH);
      return false;
    }
    return true;
  }
}

You can set your route's role group in your app-routing.module as below

export const ROUTES: Routes = [
  { 
    path: 'admin',
    component: AdminDashBoardComponent,
    canActivate: [RouteGuardService],
    data: { 
      roleCode: 'admin'
    } 
  },
  { 
    path: 'user', 
    component: UserDashBoardComponent, 
    canActivate: [RouteGuardService],
    data: { 
      roleCode: 'user'
    } 
  },
  { 
    path: 'other', 
    component: OtherPageComponent, 
    canActivate: [RouteGuardService], 
    data: { 
      roleCode: 'user'
    } 
  },
  { path: '**', redirectTo: '' }
];

I did not share the Authentication service for brevity what it can do is simply comparing the roleCode of user and route.data.roleCode. You can also integrate your authentication logic into this RouteGuardService if user is not logged in you can redirect it to loginpage again.

All of this was to prevent unauthorized access to your pages.

Your requirement as to redirecting to the correct page after login sounds like you want a dynamic home page. Redirecting depending on role group right after login would not be a good practise.

You can redirect in your Home Page Component's ngOnInit instead. This provides a better design.

export class HomePageComponent {  
...
    ngOnInit() {
        if (this.auth.isAuthorized('admin')) {
          this.router.navigateByUrl('/admin');
        } else if (this.auth.isAuthorized('user')) {
        this.router.navigateByUrl('/user');
    } 
}
talhature
  • 2,246
  • 1
  • 14
  • 28
  • 1
    Hi Talha, thanks for reply. I look at the tutorials, but as I am confused and have not used route guards yet, I cannot get the key parts. So, could you helps me pls on the following issues? Using route guards seems to be better abut, I am not sure if it solve my problem. In my scenario, I get the user's role and then redirect the user according to his role. But have no idea about the routers based on role. Any idea? –  Aug 05 '19 at 10:36
  • 1
    Im sorry, I had not understand your question well. Im editing my answer accordingly. – talhature Aug 05 '19 at 10:52
  • 1
    Sorry, I cannot explain well. I just wondering, in route guards, is there an approach by getting the user's role (from database) and then redirect it automatically based on a rule? I also look at https://codinglatte.com/posts/angular/role-based-authorization-in-angular-route-guards/ but do not see how the user forwarded. Shortly, I need an up-to-date sample with minimum implementation. I use Angular 8. Thanks and voted up ;) –  Aug 05 '19 at 11:00
  • 1
    Thanks for the upvote :) Yes most of the tutorials do not cover a redirection requirement as you do. I updated my answer. Actually the real answer is at the end but I had to mention all other route guard stuff before that. – talhature Aug 05 '19 at 11:46
  • Many thanks for detailed explanation. I think it would be good practice for me to use Route Guards as you said. Now I am implementing the service. But I am not sure if the `ngOnInit()` part of the `HomePageComponent` should be used when using Route Guard approach. should I use that part or should I check roles in the Authentication Service that you did not posted. Is there any necessary part except from your answer? –  Aug 05 '19 at 14:05
  • @hexadecimal ngOnInit part is just for redirection to the required page after login. Route Guard is for preventing unauthorized access it will be required anyway. If you do not implement route guard, a user can access admin dashboard by typing the url. – talhature Aug 06 '19 at 13:12
  • Thanks a lot for your helps. I marked as answer ;) On the other hand, Route Guard part is ok, but I am not sure if I will need to check user role in the other parts of the application I addition to after login. For example there is 2 dashboard page; user/dashboard and admin/dashboard. When a user want to go dashboard, I think I need to check the user role again if I do not create 2 different route for admin and user as above. Any idea? –  Aug 06 '19 at 19:27