Angular2 Firebase Set User

I am trying to set user properties or user attributes using the auth.updateProfile method, but it only saves the displayName property because it is mentioned in docs :

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

Now the problem is how to set user properties for the user so that I can get them in FirebaseAuthState

Question: Why do I need to save custom properties with each user?

Answer: Because I am working with Auth Guard to activate a specific route using the role property, which is saved in the sample database:

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

But I want one more check to verify that the user has a patient role that I saved when creating the user above, for example: return user.role == 'patient'

+5
source share
2 answers

Existing identity providers in Firebase Authentication cannot add custom properties. If you want to add custom properties, you will either have to implement a custom identity provider (see minting custom tokens in a trusted process and logging in with a custom token ) OR do a client-side look for additional information from an alternative data source (for example, Firebase database).

+1
source

Perhaps you can do something like this:

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

This is pretty far-fetched, but it might work. Or help you find the answer.

0
source

Source: https://habr.com/ru/post/1266329/


All Articles