AuthGuard:Angular 5 + Firebase中的OnAuthStateChanged VS检查令牌

时间:2018-02-13 21:14:27

标签: angular firebase authentication firebase-authentication angular5

每次用户注册时,以下代码都是例外:

[{"domain":"usageLimits","reason":"dailyLimitExceededUnreg","message":"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.","extendedHelp":"https://code.google.com/apis/console"}],"code":403,"message":"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."}

getToken方法如此定义:

this.router.navigate(['/']);
firebase.auth().currentUser.getToken()
   .then(
      (token: string) => this.token = token
    )

我保存了令牌,因为我有一个Guard,用于检查用户是否有令牌的路由:

getToken() {
   firebase.auth().currentUser.getToken()
     .then(
       (token: string) => this.token = token
      );
   return this.token;
}

现在,我刚刚阅读了Firebase文档,这是一个很好的做法,可以使用 onAuthStateChanged()来检查用户是否已登录:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
   return this.authService.isAuthenticated();
}

那么,定义一个(有效)用户是否使用Angular + Firebase在应用程序中签名的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

我使用此函数来检查用户是否已登录(使用angularfire2,这是一个很大的帮助,因为它以Angular方式为您提供了对firebase js sdk https://github.com/angular/angularfire2的包装器):

isLoggedIn(){

var promise = new Promise((resolve, reject) => {

  this.afAuth.authState.subscribe(res => {
    if (res && res.uid) {
      console.log('user is logged in');
      resolve(true);
    } else {
      console.log('user not logged in');
      resolve(false);
    }
  });
});

return promise;

}

这是您使用该功能的方法:

this.auth.isLoggedIn().then(
    (val) => {
      if(val){

        //Do your re-direct

      }else{
        //send alert or something
      }
    }
);