Search code examples
typescriptangular2-services

Why auth service don't remember authentication?


I have an auth guard and auth service which work correctly. But when I trying to open my application in a new browser tab I'm not logged in. My app required the login from me again. I think auth service must remember me while application doesn't restart, but isn't work. How to change this for remembering me without entering login and password for each new tabs?

@Injectable()
export class AuthService {

  private loggedIn = false;

  get isLoggedIn() {
    return this.loggedIn;
  }

  constructor(private router: Router) {
  }

  login(user: User) {
    this.loggedIn = true;
    window.localStorage.setItem('user', JSON.stringify(user));
    this.router.navigate(['/vds-list']);
  }

  logout() {
    this.loggedIn = false;
    window.localStorage.clear();
    this.router.navigate(['/login']);
  }
}

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

  constructor(private authService: AuthService, private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    console.log(state.url);
    if (this.authService.isLoggedIn) {
      return true;
    } else {
      this.router.navigate(['/login'], {
        queryParams: {
          accessDenied: true
        }
      });
      return false;
    }
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.canActivate(childRoute, state);
  }
}

I have a loggedIn variable and isLoggedIn method must return true after successful authentication once, but its work only for the same tab, unfortunately. Or other words why AuthService#loggedIn is false but I'm authenticated.


Solution

  • You need to read the user from localStorage first, in new tabs (or page refreshes).

    Try adding this to constructor of AuthService:

    try {
      let userJson = window.localStorage.getItem('user');
      let user = JSON.parse(userJson);
      this.isLoggedIn = !!user;
    } catch (e) {
      // no user
    }