Keeping emails synchronized between Firebase auth and database - firebase

I am using Firebase Web for a SaaS solution. My purpose is to have access to users' email at any time, either for sending notifications or triggering alerts from the backend.
For security reasons, Firebase auth does not allow to list users' email or to fetch emails based on user IDs. As a consequence, I keep a copy of the email into a specific collection in the Firebase database when a user account is created. The copy is made by a Cloud function that is triggered on user creation (following guidelines: https://firebase.google.com/docs/auth/extend-with-functions).
Thanks to the copy available in the Firebase database, I can access users' email. However, my issue is when a user changes his email.
Firebase auth provides the updateEmail function that returns a promise. I use this last to update the email in Firebase auth. Then, when the promise resolves I update the user email in the Firebase database. However, this has a major drawback: all the logic is performed on the client side and since both operations are not performed in a transaction if the client refreshes or closes his browser (or assume it crashes), then it is possible that Firebase auth is updated but not the Firebase database, thus leading to an inconsistent state.
I looked at the documentation, expecting the possibility to trigger a Cloud function when user auth information is updated. Unfortunately, I cannot find such a feature.
Another solution I thought about is to update the database from the Web client. Then, this last triggers a Cloud function that updates Firebase auth with the admin SDK. This last solution works but bypasses the check performed by updateEmail that ensures the new email is not used by another account. Also, the account hijacking protection performed by updateEmail is evicted, which is really bad from a security point of view.
Any idea to solve this problem properly is welcome.

Here are a couple of options:
When calling updateEmail, update the email in your database first before calling updateEmail. THowever, if an error occurs, you need to catch it and undo that change in your db.
When a user wants to updateEmail, send their id token and new email to your server or firebase function http endpoint. There you verify the ID token with the admin SDK, then use the client SDK require('firebase'), using the uid from the ID token, admin.auth().createCustomToken(uid), then using client SDK, firebase.auth().signInWithCustomToken(customToken). You can then call user.updateEmail(newEmail) on the backend and save the email.
Always save the uid only and just use Admin SDK admin.auth().getUser(uid) to look up the user and get their email. This guarantees you get the user's latest email as you will not be able to catch the email revocation if the user chooses to do so.
No need to save anything. Use the CLI SDK to download all your users and their emails. Check https://firebase.google.com/docs/cli/auth#authexport
This is also better as you will always be able to get the latest email per user even if they revoke the email change.

Related

Synchronize users created with Firebase Auth to my custom backend

I want to use Firebase Auth for my user login/registration process. Everything else should be handled by my own backend (spring boot app + postgres db).
Now I'm asking myself how I can synchronize a new created user to my user table in postgres. I thought about the following:
REST call through client - Everytime I get a success event from the firebase sdk I call an additional request to my backend which sends uid, username etc.
Problem: What if my backend call fails but the register process was successful ? That would lead to an inconsistent state since (at least thats what I understanded) I can't easily rollback. That would lead to situations where a user can login into my app without my backend knowing the user. This would crash/ invalidate all my following queries (e.g. search after user xyz would lead to no result even though he/she exists)
Check the existence of the user in the postgres database
Here I would query the uid from the database (which I got from the jwt) and create a new user if it doesn't exists in every incoming request.
Problem: The user query is a unnessecary overhead for every incoming request.
Trigger with cloud functions - When I understood it right firebase auth is firing events when a new user is created in cloud functions. This could be used to make the external api call.
Problem: I dont know what happens when my external rest call fails at this point. Can I rollback the registration ? Will I be ever catch this event again ? I also proably would have an eventual consistency situation, since I dont know when the cloud function triggers. Furthermore I would prefer not to include cloud functions to my stack
Is there any way how I could do this in a transactional manner ? Did anyone else tried is using sth simular ?
Thanks for every help!
The easiest way is actually to not synchronize auth data, but instead decode and verify the ID token of the user in your backend code.
This operation is (by design) stateless, although Firebase's own backend services often implement a cache of recently decoded tokens to speed up future calls with the same ID token.
Apparently, I finally came up with a different solution:
Register user per Firebase SDK (e.g. with email + pw method)
Make a post-call to my own registration api including the resulting uid from the previous step and some metadata
API creates a new user including a column with the UID + Fetches the firebase token of the user and adds an internal claim that references to the internal Postgres UUID via Admin SDK.
Frontend gets the created user and hard refreshes (very important, since the previously fetched token won't contain the newly added claim !) the firebase token and verifies that it contains the token. If it does -> everything is cool, if not some oopsie happened :) That will require a request retry.
Later when you start your app you can just check if the passed token contains the custom claim, if not open the sign up/sign in page.
Every endpoint except the one for registration should check if the claim is set. If not just forbid the request.
How to set custom claims:
https://firebase.google.com/docs/auth/admin/custom-claims#set_and_validate_custom_user_claims_via_the_admin_sdk
You can use the Firebase Admin SDK to create the user account from your back-end instead of from the client.
So first you create the user in your database, then grab the ID and use it to create a user with the same ID in Firebase.
If all goes well, send a confirmation to the client and sign it in using the same credentials they entered.
Why not creating an endpoint in your backend service and call this endpoint when a client side authentication succeeds?
This method should do 2 things:
decode token to get access to Firebase user object (Firebase Admin)
Compare Firebase user with your internal user table. if it doesn't exist you can create it using firebase user object, otherwise do nothing.
This solution allows you to do other nice things as well (Syncing user info between Firebase and your internal db, providing a way to let a frontend know if this user is new or not, ...) at a relative small cost (1 get call per sign in)

Firebase Auth subscription

I'm working on a app which uses Firebase Auth to signup and login, but I'm facing some things which I don't know how to start. Users need to registrate on a website and they need to pay a subscription before the user is created in firebase, when they don't pay anymore, the user account should be disabled. So basically, users registrate on the web and after they pay, they can log into the app with their credentials.
Edit:
Since yesterday I'm trying to implement either mollie or stripe, but I can't get myself started, online there are very few video's about payments in combination with firebase
There are basically two ways off the top of my headto do this:
A) Secure but it involves cloud function and creating custom authentication token to login.
User registers with email.
User keys in login information and posts to cloud function.
Find user's uid/email and check for password.
Fetch the subscription document and check if it is active.
If it is inactive, return an error message accordingly.
If it is active, create an authentication token and return to user to login.
B) Client side checking, less secure but will do the trick.
User logins
Fetch subscription using user's uid. Check its validity
Force redirect user to subscription page if it is inactive with
error message. OR Autologout user if it is inactive with error message.
May I also suggest Stripe for their subscription service (Not sponsored)? Unless you already have an implementation in place.

Flutter Firebase, logout other user than me

In my Flutter management application, I would like to disconnect a user other than the one I am logged in with.
I use Firebase as my database, and use email and a password to log in. I don't use a token
I know that in order to disconnect the user I am currently logged in with, it has to be done like this:
FirebaseAuth.instance.signOut();
I can't figure out how to disconnect another user.
In the Firebase client-side SDKs, you can only sign out the currently signed in user. There is no way to sign out a user on another device.
If you want to add user management functionality to your client-side application, you'll want to use a combination of the client-side SDK and a server-side Admin SDK to build this functionality:
Use the Admin SDK in a trusted environment (such as a server you control, or Cloud Functions) to implement the user management functionality.
Create an endpoint that clients can call that exposes this functionality, for example as a callable Cloud Function.
In that endpoint be sure to check whether the user is authorized, for example by checking their ID token to see if it has a certain UID or custom claim.
Call the custom endpoint from your client-side code.

Are "Firebase Auth" custom claims eventually consistent?

I am using Firebase Auth for SMS login and I want to add to new users a custom "countryCode" claim to the token.
After the Android app validate the SMS code, it invoke the account service in my backend to create the new account and
in that step add the custom claim with Firebase Admin SDK.
The app need to do a force refresh token to get the new claim.
I need to know if after adding the "claim" the update is eventually consistent or not.
If it is eventually consistent I can't guarantee that the refreshed token have the new claim.
I'm not entirely sure what you mean by "eventually consistent" in this context, but you can be sure that these two situations are reliable:
After writing the claims successfully using the Firebase Admin SDK, an immediate call to re-read the claims using the SDK will return the same previously written claims.
A client token refresh that happens after a change to custom claims on the backend will result in the client seeing the new claims. You will need to make sure that the client doesn't refresh until the claims are successfully committed, so that there is no race condition. This could involve the backend signaling to the frontend by changing something in Realtime Database or Cloud Firestore to indicate to the listening client that it's time to refresh the claims. You could use a timestamp that indicates the time of the last write of claims for the user, and the client could compare that to the time it last refreshed.

How to disallow disposable email in firebase auth email provider signup?

We are using firebase auth and firebase auth UI to authenticate a user.
We want to disallow or block those user's, who is trying to use a temporary mailbox for signing up (eg: https://www.mailinator.com).
There are 2 proposed solutions:
Do a client-side validation for the email ID? (Difficult to manage a blacklist of email providers in the client. Also, people can still use API to hack it).
After the user signs up, on onCreate user event, we can trigger a firebase function to validate the email ID against the blacklist, then we can disable or revoke the account. But here,
if we are disabling the user, he/she will get access to our app for next 1 hour as the client already gained the ID token.
If we are revoking refresh token, we'll have to again wait for 1 hour or write the rule to make a query to Firestore to check if user access is revoked. (Better if we can avoid this query)
Is there a better or native way to solve this issue?
If we are not getting any other solutions, we'll choose to go with 2nd option (revoking refresh token).
I would do a combination of both solutions you proposed. Doing the client side check will trip up most people and for the more tech savvy that try to get around it, your onCreate trigger will deal with them.
You could also add their uid to a blocked list in the realtime database from your onCreate trigger.
Then you can listen to it on the client and log them out. And for database rules you can check if they are in the block list and so block the read/write rule.
a regularly updated service to check DPA is already being maintained.
Do a simple get request to:
https://open.kickbox.com/v1/disposable/{user_email}
this would return the response
{
"disposable": true
}
if email id is disposable.
you can send the get request with complete email id or just the domain.
e.g. https://open.kickbox.com/v1/disposable/jamond67#zdecaesgl.com
or https://open.kickbox.com/v1/disposable/zdecaesgl.com

Resources