Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current route guard

I'm making an app with some protected pages inside This pages are accessible only for registered users. Some times i should check session for timeout or after change browser tab. If user already exit in other tab or session expired, the app should redirect user to login page.

I'm using guards to protect pages so i think it correct way to check current route by his guard. Page should by redirected if user session expired/closed and current route uses certain guard.

Could anybody help to get guards of the current route?

I checked docs for Router and ActivatedRoute and don't find any information about that.

like image 639
avvensis Avatar asked Feb 08 '17 14:02

avvensis


2 Answers

I was facing this issue also. So I did a little resarch and fiddling and developed this solution:

Assuming the AuthService is implemented like in https://angular.io/guide/router#canactivate-requiring-authentication.

In the AuthService add the following:

Logout() {
// (logout logic here)
  var currentRouteConfig = this.router.config.find(f=>f.path == this.router.url.substr(1));
  if(currentRouteConfig != null && currentRouteConfig.CanActivate != null)  {
    this.redirectUrl = this.router.url;
    this.router.navigate(['/login'])
}

The substr(1) just removes the leading '/' as the path in the router config is without it.

Please keep in mind, that this is a naive implementation assuming that the canActivate is always implementing an authentication guard. Other logic may need deeper checking for authentication guards.

like image 131
ace lafit Avatar answered Nov 15 '22 04:11

ace lafit


I face exactly the same issue. Here is a scenario to better understand the need. Imagine you have a website where some pages are protected and some are not. A guard is used to protect appropriate pages. Now imagine user is on protected page (let's say viewing profile) and clicks 'Logout' button. What should happen? User should be redirected to a home page. But if user is on a page that is not protected by guard nothing should really happen. Of course it's possible to check it on every signle page if redirect should happen but it's not the best solution. A better solution would be to handle this situation in AuthService, where logging out is acctually happens but for that someone needs to know if currectly active route is protected by guard or not.

like image 33
eugene_2005 Avatar answered Nov 15 '22 03:11

eugene_2005