0

I have created an auth guard like below based on the auth token from local storage. If the token is not present in local storage, it is working and redirecting the user back to the login page. But if the token is present in storage then I still can go to the login page.

Question: If the token is present in storage then a user will not be able to route back to the login page.

Guard.ts

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    const isLoggedIn = this._spotify.isAuthenticated();
    if (isLoggedIn) {
        // authorised so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this._logger.error('Not authenticated, redirecting...');
    this._router.navigate(['/'], {
        queryParams: { returnUrl: state.url }
    });
    return false;
}

Auth Service

isAuthenticated(): boolean {
    if (localStorage.getItem('accessToken')) {
        return true;
    }
    return false;
}
C.Champagne
  • 5,381
  • 2
  • 23
  • 35
RAHUL KUNDU
  • 745
  • 2
  • 12
  • 33
  • 1
    You can have multiple guards, one to prevent guests from seeing private content, and another to prevent logged-in users to getting to the login page, if that makes sense for your application. – Eyeslandic Jun 27 '21 at 08:28

1 Answers1

1

If you have some route like so

{ path: '/login', component: LoginComponen}

you can add a new authGuard for it specifically

export class LoginGuard implements CanActivate {
  constructor(private _spotify: AuthService, private router: Router) {}

  canActivate(): Observable<any> {
    const isLoggedIn = this._spotify.isAuthenticated();
    if (!isLoggedIn) {
      return true;
    }
    return this.router.navigate(['/'])
  }

and then add it to your route

{ path: '/login', component: LoginComponent, canActivate: [LoginGuard] }
Shraga
  • 67
  • 1
  • 8