Angular2 Firebase设置用户自定义属性

时间:2017-04-04 19:30:59

标签: angular typescript firebase angular2-routing

我一直在尝试使用auth.updateProfile方法设置用户自定义属性或属性,但它只保存displayName属性,因为它在docs中提及:< / p>

this.af.auth.createUser({
   email: formData.value.email,
   password: formData.value.password,
}).then((user) => {
   let userProfile = formData.value;
   userProfile.role = AuthService.ROLE_PATIENT;
   userProfile.displayName = `${formData.value.firstName} ${formData.value.lastName}`;
   user.auth.updateProfile(userProfile).then(function(){
   this.router.navigate(['/']);  
}); 

现在问题如何设置用户的自定义属性,以便我可以在FirebaseAuthState

中获取它们

问题:为什么我需要为每个用户保存自定义属性?

答案:因为我正在使用Auth Guard使用保存在数据库示例中的role属性来激活特定路由:

canActivate(route: ActivatedRouteSnapshot,
              state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    //Currently I'm using this which only check that user is logged in or not
    return this.auth
      .take(1)
      .map((authState: FirebaseAuthState) => !!authState)
      .do(authenticated => {
        if (!authenticated) this.router.navigate(['/login']);
      });   
  }

但我想要再检查一下,确认用户在创建上述用户时已经保存了患者的角色,例如:  return user.role == 'patient'

2 个答案:

答案 0 :(得分:1)

Firebase身份验证中的现有身份提供程序无法添加自定义属性。如果要添加自定义属性,则必须实现自定义标识提供程序(请参阅minting custom tokens in a trusted processsigning in with a custom token)或执行client-side look-up of the additional information from an alternate data source(例如Firebase数据库)。

答案 1 :(得分:0)

也许你可以这样做:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    //Currently I'm using this which only check that user is logged in or not
    return this.auth
      .take(1)
      .map((authState: FirebaseAuthState) => {

        return this.af.database.list('/path/to/account').first().map((account: IAccount) => {

          if (authState && account.role === 'patient') {
            return true;
          }
          else {
            return this.router.navigate(['/login']);
          }
        });
      });
  }

这很牵强,但可能会奏效。或者帮助您找到答案。