Skip to content

Instantly share code, notes, and snippets.

@ShurikAg
Created April 8, 2016 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShurikAg/3c8afc05765cf1b5941b3cc3f81523df to your computer and use it in GitHub Desktop.
Save ShurikAg/3c8afc05765cf1b5941b3cc3f81523df to your computer and use it in GitHub Desktop.
import {Directive, Injector, Attribute, ElementRef, DynamicComponentLoader, Input} from 'angular2/core';
import {Router, RouterOutlet, RouteParams, ComponentInstruction} from 'angular2/router';
import {AuthenticationService} from '../services/authentication.service';
@Directive({
selector: 'secure-outlet'
})
export class SecureRouterOutlet extends RouterOutlet {
@Input()
signin: string;
@Input()
unauthorized:string;
constructor(_elementRef: ElementRef,
_loader: DynamicComponentLoader,
private parentRouter: Router,
@Attribute('name') nameAttr: string,
private authService: AuthenticationService,
private injector:Injector) {
super(_elementRef, _loader, parentRouter, nameAttr);
}
activate(nextInstruction: ComponentInstruction): Promise<any> {
var params = this.getAllRouteParams(this.injector);
var isAuthorized = this.authService.isAuthorized(nextInstruction, params);
if (isAuthorized) {
return super.activate(nextInstruction);
}
if (this.authService.isLoggedIn()) {
var ins = this.parentRouter.generate([this.unauthorized]);
return super.activate(ins.component);
} else {
var ins = this.parentRouter.generate([this.signin,{url:location.pathname}]);
return super.activate(ins.component);
}
}
reuse(nextInstruction: ComponentInstruction): Promise<any> {
return super.reuse(nextInstruction);
}
getAllRouteParams(injector:Injector) {
let params: Object = null;
while(injector) {
const routeParams = injector.getOptional(RouteParams);
if (routeParams) {
if (params === null) {
params = {};
} else {
params = Object.create(params);
}
Object.assign(params, routeParams.params);
}
injector = injector.parent;
}
return params;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment