1

I have to set authentication for a user where in only a specified user can access a button, for that i used localStorage, such that i hide the button when any user other than admin is trying to access it.

But there is also another way a user can access the buttons , via links like :

http://localhost:4200/#/master-system/add-user

or

http://localhost:4200/#/master-system/update-user.

So to disable the child (i guess it is the child , please correct me if i am wrong), i added canActivateChild in authguard.ts file and some changes in app.routing.ts file, but it doesn't work.

Also, i have many routing.ts files. Its like, i have 5 components inside master-system and this master-system has its own routing.ts file and this master-system.routing.ts file is included in the main routing.ts file. SO have to deactivate the child ,when its not the admin user.

authguard.ts

  import { Injectable } from '@angular/core';
   import { Router, CanActivate, ActivatedRouteSnapshot,          
 RouterStateSnapshot, CanActivateChild } from '@angular/router';


  @Injectable()


    export class AuthGuard implements CanActivateChild, CanActivate {
    expectedRole: any;
    accessId:boolean=false;
    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)           
       {
    if (localStorage.getItem('CurrentUser')) {

        console.log("IN AUTHGUARD", localStorage.getItem('CurrentUser'));
        console.log("inside CanActivate - true  ")
        return true;

      }
      else {

        this.router.navigate(['/pages/login'], { queryParams: { returnUrl:       

      state.url } });
        console.log("inside CanActivate - false -  

       this.router.navigate(['/pages/login'] ")
        return false;
          }
       }

     canActivateChild(route: ActivatedRouteSnapshot, state:            
     RouterStateSnapshot) {
     this.expectedRole = route.data;

        if ( localStorage.getItem('Access') == "18") {

              this.accessId = true;
              localStorage.setItem('accessId',            
      JSON.stringify(this.accessId));
              var output = localStorage.getItem('accessId');
              console.log("localStorage.getItem('accessId') = ",output)

             return true;
        }

        else 

        {
            this.router.navigate(['/pages/login'], { queryParams: {         
       returnUrl: state.url } });

            return false;            }

     }
     }

master-system-routing.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import{ AuthGuard } from '.././authguard/authguard';
    import { MasterSystemsComponent } from './master-systems/master-   
   systems.component';
    import { AddSystemComponent } from './add-system/add-  
     system.component';
     import { UpdateSystemComponent } from './update-system/update- 
     system.component';



   const routes: Routes = [
    {
       path: '',
       data: {
        title: 'Master System'
       },
       children: [
        {
            path: 'master-systems',
            component: MasterSystemsComponent,
            data: {
                title: 'Master Systems'
            }
          },
          {
            path: 'master-interface',
            component: MasterInterfaceComponent,
            data: {
                title: 'Master Interface'
            }
        },
        {
            path: 'master-user',
            component: MasterUserComponent,
            data: {
                title: 'Master User'
            }
        },
        {
            path: 'master-group',
            component: GroupComponent,
            data: {
                title: 'Master Group'
            }
        },
        {
            path: 'master-role',
            component: RoleComponent,
            data: {
                title: 'Master Role'
            }
        },
        {
            path: 'add-system',
            component: AddSystemComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-system',
            component: UpdateSystemComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-interface',
            component: AddInterfaceComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-interface',
            component: UpdateInterfaceComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-user',
            component: AddUserComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-user',
            component: UpdateUserComponent,
            canActivateChild:[AuthGuard],
            data: {
                title: 'Update',
                expectedRole: '18'
            },

        },
        {
            path: 'add-group',
            component: AddGroupComponent,
            canActivateChild:[AuthGuard],
            data: {
                title: 'Add',
                expectedRole: '18'
            }
        },
        {
            path: 'update-group',
            component: UpdateGroupComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-role',
            component: AddRoleComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-role',
            component: UpdateRoleComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'master-transaction',
            component: TransactionComponent,
            data: {
                title: 'Transaction'
            }
        },
        {
            path :'transaction-payload',
            component:PayloadComponent,
            data:{
                title:'Payload'
            }
        },
        ]

        }
       ];

   @NgModule({
   imports: [RouterModule.forChild(routes)],
   exports: [RouterModule]
   })
   export class MasterSystemRoutingModule { }

app.routing.ts

   import { NgModule } from '@angular/core';
   import { Routes, RouterModule } from '@angular/router';

  // Layouts
   import { FullLayoutComponent } from './layouts/full-layout.component';
    import { SimpleLayoutComponent } from './layouts/simple- 
    layout.component';

    import{ AuthGuard } from './authguard/authguard';


    export const routes: Routes = [
   {
    path: '',
     redirectTo: 'pages/login',
     pathMatch: 'full',
     },
     {
    path: '',
    component: FullLayoutComponent,

    children: [
     {
    path: 'dashboard',
    loadChildren: './dashboard/dashboard.module#DashboardModule',
    canActivate:[AuthGuard],

  },
  {
    path: 'components',
    loadChildren: './components/components.module#ComponentsModule',
    canActivate:[AuthGuard],


    },
     {
    path: 'icons',
     loadChildren: './icons/icons.module#IconsModule'
     },
    {
    path: 'master-system',
    loadChildren: './master-system/master-   
    system.module#MasterSystemModule',
    canActivate:[AuthGuard],

     { 
       expectedRole: '1'
     }] ,
     { 
       expectedRole: '1',
       }

     },

    {
    path: 'mapping',
    loadChildren: './mapping/mapping.module#MappingModule',
    canActivate:[AuthGuard],

  },
   {
    path: 'widgets',
     loadChildren: './widgets/widgets.module#WidgetsModule'
      },
     {
    path: 'charts',
    loadChildren: './chartjs/chartjs.module#ChartJSModule',
    canActivate:[AuthGuard],
    canActivateChild:[AuthGuard],
      canActivateChild:[AuthGuard],
     data: [{ 
       expectedRole: '18'
     }]
    children:[
       {

      component: MasterInterfaceComponent
       }
        ],
    data: [{ 
      expectedRole: '18'
    }]
  },
  {
    path: 'search',
    loadChildren: './search/search.module#SearchModule',
    canActivate:[AuthGuard],
     canActivateChild: [ AuthGuard ],
     children: [
       {
          path: ':id',
           component: ArticleEditComponent
        }
       ] 

  },
  {
    path: 'eai',
    loadChildren: './eai/eai.module#EaiModule',
    canActivate:[AuthGuard],


  },
  {
    path: 'report',
    loadChildren: './report/report.module#ReportModule',
    canActivate:[AuthGuard],
      canActivateChild:[AuthGuard],
       data: [{ 
       expectedRole: '18'
        }]

       },

       ]
      },
     {
    path: 'pages',
   component: SimpleLayoutComponent,
    data: {
    title: 'Pages'
     },
     children: [
        {
        path: '',
       loadChildren: './pages/pages.module#PagesModule',
       }
      ]
      }
     ];

    @NgModule({
     imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}
1
  • Seems to me that you are going about it the wrong way, you can do the authentication on path at the api level, leaving you to handle the responses received from a request launched. Commented Jun 3, 2018 at 11:21

2 Answers 2

1

I think, your problem is about permission of urls. each url point to a component. I have a simple solution. when you save authentication in localStorage, also save role of user. then in ngOnInit method check, if user is not admin, for example, do not access to this component.

if(localStorage.getItem('role') != 'admin'){
    this.router.navigate(['/']);
}

when call a url, in fact call a component, and in a component ngOnInit is first thing that run, then if a user do not have permission, go to home page.

Sign up to request clarification or add additional context in comments.

Comments

0

have you try use canActiveChild in path:master-system?

const routes: Routes = [
  ...
  {
    path: 'master-system',
    loadChildren: './master-system/master-system.module#MasterSystemModule',
    canActivateChild: [AuthGuard]
  }
  ...
];

2 Comments

no it doesn't work. Can you check this - stackoverflow.com/questions/50677565/…
can you create an online example in stackblitz? it's can save your more time and get an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.