如何禁用用户通过URL2 + / angular4中的URL访问页面

时间:2018-06-03 11:14:09

标签: angular typescript authentication

我必须为只有指定用户可以访问按钮的用户设置身份验证,因为我使用了localStorage,这样当我以外的任何用户试图访问它时我隐藏按钮。

但是,用户还可以通过以下链接访问按钮:

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

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

所以要禁用孩子(我猜它是孩子,请纠正我,如果我错了),我在authguard.ts文件中添加了canActivateChild,并在app.routing.ts文件中添加了一些更改,但它不起作用

另外,我有很多routing.ts文件。就像,我在master-system中有5个组件,这个master-system有自己的routing.ts文件,这个master-system.routing.ts文件包含在主要的routing.ts文件中。当不是管理员用户时,必须停用该孩子。

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;            }

     }
     }

主系统用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 {}

2 个答案:

答案 0 :(得分:0)

我认为,你的问题是关于网址的许可。每个url指向一个组件。我有一个简单的解决方案。当您在localStorage中保存身份验证时,还会保存用户的角色。然后在ngOnInit方法检查中,如果用户不是管理员,例如,不要访问该组件。

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

当调用url时,实际上调用一个组件,并且在组件中首先运行ngOnInit,然后如果用户没有权限,则转到主页。

答案 1 :(得分:0)

您是否尝试在path:master-system中使用canActiveChild?



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