Search code examples
angularangular-router

Angular7 route redirect user


If a user logs in, it automatically redirects to the route: '' and I have the token stored in localStorage.

However, if a logged in user manually types in the url route: /login he should be routed in the route: '' and that is what I want to achieve.

What I did was to add a validation in my OnInit() inside my LoginComponent and it's working. But how can I achieve this in my AuthGuard? I am thinking of getting the requested route if route: /login and navigate to route: '' if already logged in.

Route:

{ path: '', component: PostListComponent },
{ path: 'create', component: PostCreateComponent, canActivate: [AuthGuard] },
{ path: 'edit/:postId', component: PostCreateComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }

AuthGuard:

const currentRoute = route.url[0].path;
const isAuth = this.authService.getIsAuth();

if (!isAuth) {
  this.router.navigate(['/login']);
}

if (currentRoute === '/login') {
  this.router.navigate(['/']);
}

console.log(currentRoute);
return isAuth;

LoginComponent:

ngOnInit() {
 const isAuth = this.authService.getIsAuth();
 if (isAuth) {
   this.router.navigate(['/']);
 }
}

UPDATE: I updated my AuthGuard to check the current route but it is not getting the route if it is manually typed into the address bar.


Solution

  • After further review of my code and stackoverflow browsing, I came with a solution but I'm uncertain with the possible security. If you have a better approach, please share.

    Route:

    { path: 'login', component: LoginComponent, canActivate: [AuthGuard] }
    

    AuthGuard:

    const currentRoute = route.url[0].path;
    let isAuth = this.authService.getIsAuth();
    
    if (isAuth) {
      if (currentRoute === 'login') {
        this.router.navigate(['/']);
      }
    } else {
      if (currentRoute === 'login') {
        isAuth = true;
      } else {
        this.router.navigate(['/login']);
      }
    }
    return isAuth;
    

    The isAuth returns boolean if authenticated or not and here in AuthGuard I used let and changed the value to true.