user26776
user26776

Reputation: 131

Deny access to routes in Angular js 2

I have a file with the routes and wanted to deny access to some when the user does not have the login done ,how can i do this?

my routes

import { provideRouter, RouterConfig }  from '@angular/router';
import {SymfonyComponent} from './symfony.component';
import {Symfony2Component} from './symfony2.component';
import {Symfony3Component} from './symfony3.component';
import {LoginComponent} from './login.component';

const routes: RouterConfig = [
  {
    path: 'all',
    component: SymfonyComponent
  },

  {
    path: 'one',
    component: Symfony2Component
  },
   {
    path: 'post',
    component: Symfony3Component
  },
  {
    path: 'login',
    component: LoginComponent
  },
];

export const appRouterProviders = [
  provideRouter(routes)
];

Upvotes: 3

Views: 3090

Answers (1)

jhhoff02
jhhoff02

Reputation: 1210

You can do this with Angular2's AuthGuard, check out this AuthGuard documentation.

Here is an example of its use in app.routes.ts:

import {AuthGuard} from './app/common/guards/auth.guard';
import {HomeComponent} from './app/home/home.component';

export const Routes : RouterConfig = [{
            path: 'home',
            component: HomeComponent,
            canActivate: [AuthGuard]
        }]

Then you need to create a guard, it'll look something like this:

import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {FooAuth} from 'foo';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate { 
constructor(
    private _fooAuth: FooAuth,
    private _router: Router
){}
canActivate() : Observable<boolean>{
    return this.isAllowedAccess();
}
private isAllowedAccess() {
    if(!this._fooAuth.currentSession) {
        this._router.navigate(['/login']);
        return Observable.of(false);
    }
    return Observable
        .fromPromise(this._fooAuth.validateSession(this._fooAuth.currentSession))
        .mapTo(true)
        .catch(err => {
            this._router.navigate(['/login']);
            return Observable.of(false)
        });
}

Once you set up the guard, you can add canActivate: [AuthGuard] to each route and it will check your auth logic each time you change routes. (your auth logic will vary depending on your login authentication service/module)

Upvotes: 5

Related Questions