Created
July 8, 2017 19:57
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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