Skip to content

Instantly share code, notes, and snippets.

@theoomoregbee
Last active July 8, 2017 19:41
Show Gist options
  • Select an option

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

Select an option

Save theoomoregbee/e42777eb28e9547e2b7478e3b3f54440 to your computer and use it in GitHub Desktop.
EVERYTHING YOU NEED TO KNOW ON SECURING YOUR ANGULAR 2+ SPA --> method to be called by canActivate and canActivateChild
/**
* this is method does the checking for us, according to the below process
* 1. check if the user is authenticated, if so check if is time to refresh token the return the observable
* so our guard can resolve it, since the retrieve method is already handling the response with `do` we just map this
* to true default so next view can check and see if the new token is valid or not
*
* 2. if the above from 1 pass through without returning it means it was false all the way
* so we handle it by passing a message and updating the redirectUrl so users can continue where they left of
* after authentication
* @param next
* @param state
* @returns {any}
*/
private performCheck(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
if (this._authService.isAuthenticated()) {
//let's check if the token will expire soon
if (this._authService.shouldIGetToken()) {
return this._authService.retrieveToken()
.mapTo(true); //resolve to true since we are already handling it before now, just return true
} else
return true;
}
this._authService.setRedirectUrl(state.url);
this._authService.message = 'Please login to continue';
this._authService.clear();
//navigate to login page
this._router.navigate(['/login']);
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment