Search code examples
javascriptangularroutesamazon-cognitoaws-amplify

Is it possible to restrict access in Angular Routing for particular :ids in a path? Using Amplify/Cognito


Say I have a routing module with the following setup:

const routes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: '', component: MainComponent,
  children: [
    { path: '', redirectTo: '/home', pathMatch: 'full'},
  { path: 'dashboard/:id', component: DashboardComponent },
  {path: '404', component: HomeComponent},
   {path: '**', redirectTo: '/404'}
]
}];

Is it possible to restrict access to the following:

https://website.com/dashboard/1 (where only users who fall into 1 can see 1) https://website.com/dashboard/2 (where only users who fall into 2 can see 2)

If a 1 goes to dashboard/2 they would be routed to an error page or vice versa. Is this possible?


Solution

  • That's the job of the Guards. You can implement canActivate function and pass to it preferable argument for the identification.

    class UserToken {}
    class Permissions {
      canActivate(user: UserToken, id: string): boolean {
        return true;
      }
    }
    
    @Injectable()
    class CanActivateTeam implements CanActivate {
      constructor(private permissions: Permissions, private currentUser: UserToken) {}
    
      canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
        return this.permissions.canActivate(this.currentUser, route.params.id);
      }
    }
    

    and after just configure your route with the guard:

    { path: 'dashboard/:id', component: DashboardComponent, canActivate:['Your Guard Name'] },
    

    On successful authentication user will be able to continue. On fail you will implement redirect logic with angular Router.