Search code examples
angularfirebasefirebase-authenticationangularfire2

AuthGuard blocks login


When I want to log into the authguard system all the time blocks this login and displays the specified message. How to fix it? It should be blocked only if I want to go to an unauthorized page for which I set a guard without logging in.

auth.service:

export class AuthService {
  private user: Observable<firebase.User>;
  authState: any;

  constructor(private afAuth: AngularFireAuth,
    private router: Router) {
    this.user = afAuth.authState;
  }

  authUser() {
    return this.user;
  }

  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('users'));
    return (user !== null) ? true : false;
  }

  currentUserId() {
    return this.afAuth.authState
  }

  signIn(email: string, password: string) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password).then(
      (user) => {
        this.authState = user;
        this.setUserStatus('online');
        this.router.navigate(['chat']);
      }
    );
  }

}

auth.guard:

export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService, private router: Router) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.auth.isLoggedIn !== true) {
      window.alert('Test!')
      this.router.navigate(['sign-in'])
    }
    return true;
  }
}

Solution

  • auth.service.ts

     isLoggedIn(): boolean {
        const user = JSON.parse(localStorage.getItem('users'));
        return (user !== null) ? true : false;
      }
    

    auth.guard:

    export class AuthGuard implements CanActivate {
      constructor(private auth: AuthService, private router: Router) { }
    
      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
         // 
        if (this.auth.isLoggedIn() !== true) { // <====
          window.alert('Test!')
          this.router.navigate(['sign-in'])
           return false;
        } 
        return true;
      }
    }