Skip to content

Instantly share code, notes, and snippets.

@theoomoregbee
Created July 8, 2017 19:57
Show Gist options
  • Select an option

  • Save theoomoregbee/31783b5509174fb1f3925ca0462b7984 to your computer and use it in GitHub Desktop.

Select an option

Save theoomoregbee/31783b5509174fb1f3925ca0462b7984 to your computer and use it in GitHub Desktop.
EVERYTHING YOU NEED TO KNOW ON SECURING YOUR ANGULAR 2+ SPA --> Role Guard
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {UserService} from "../providers/user.service";
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private _userService: UserService) {
}
/**
* this check the route if the data is existing then we move on to check if the role passed
* from the route data is among the user roles array
* @param next
* @param state
* @returns {boolean}
*/
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (next.data == null)
return true;
if (next.data.role == null)
return true;
let user = this._userService.get();
let allow = user.roles.indexOf(next.data.role) > -1;
if (allow == false)
alert("you can't go here");
return allow;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment