AuthGuard阻止登录

时间:2019-07-14 06:59:06

标签: angular firebase firebase-authentication angularfire2

当我想一直登录到authguard系统时,会阻止此登录并显示指定的消息。如何解决?仅当我要转到未经登录而设置了保护措施的未经授权页面时,才应将其阻止。

身份验证服务:

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    for (int i = 0; i < strlen(argv[1]); i++)
    {
        if (!isdigit(argv[1][i]))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
    }

    printf("Success\n");
    printf("%s\n", argv[1]);
}

auth.guard:

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']);
      }
    );
  }

}

1 个答案:

答案 0 :(得分:0)

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;
  }
}