Skip to content

Instantly share code, notes, and snippets.

@Warrenn
Created June 11, 2018 09:07
Show Gist options
  • Save Warrenn/a4401545535fc45381404ca3bcfc73c3 to your computer and use it in GitHub Desktop.
Save Warrenn/a4401545535fc45381404ca3bcfc73c3 to your computer and use it in GitHub Desktop.
ng6 rout guard
import {Injectable} from '@angular/core';
import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {AuthService} from '../services/auth.service';
@Injectable()
export class RouteGuard implements CanActivate {
constructor(
private router: Router,
private auth: AuthService
) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const { auth, router } = this;
const { allowAccessTo } = next.data;
const identity = auth.getIdentity();
if (
identity &&
allowAccessTo.indexOf(identity.role)
) {
// all good, proceed with activating route
return true;
}
if (identity) {
// TODO show ErrorForbiddenViewComponent instead of redirecting
console.log('403 Forbidden >>', next);
}
else {
// not logged in: redirect to login page with the return url
const [returnUrl, returnQueryParams] = state.url.split('?');
console.log('401 Unauthorised >>', returnUrl, returnQueryParams, next);
router.navigate(['/login'], {queryParams: {returnUrl, returnQueryParams}});
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment