英文:
Create user in my database after creating it with Firebase
问题
我有一个基于Next.js的前端和一个Express后端。身份验证由Firebase处理。用户可以使用电子邮件/密码或Google注册。
我需要确保用户不仅存在于Firebase中,还存在于我的数据库中,因为我需要一种方法将用户链接到仅存在于我的数据库中的所有其他实体。
对于电子邮件/密码,实现这一点相对简单,我只需要在我的后端上创建一个端点,通过管理SDK创建Firebase用户和我的数据库中的用户。
处理Google注册的情况更加棘手,因为我需要首先在前端上创建用户。在调用signInWithPopup
之后,我可以使用新创建的用户的uid
调用我的后端并将其添加到那里,但如果我的后端宕机了怎么办?
一个选项是在后端上有一个中间件,如果用户尚不存在,则创建用户,但然后我必须在每个请求上执行此检查。
关于如何最好处理这个问题的想法?
英文:
I have a Next.js frontend and an Express backend. The auth is handled by Firebase. Users are allowed to sign up with email/password or through Google.
I need to make sure that users also exist in my database, not just in Firebase, as I need a way to link the user to all other entities that exist only in my database.
Achieving this for email/password is rather simple, I just need an endpoint on my backend that creates both together, the firebase user through the admin sdk and a user in my database.
Handling this for the Google sign up is more problematic as I need to first create the user on the frontend. After calling signInWithPopup
, I could call my backend with the uid
of the newly created user and add it there, but what if my backend's down?
An option would be to have a middleware on the backend that creates the user if it doesn't already exist, but then I have to do this check on every request.
Thoughts on how to best handle this?
答案1
得分: 0
我可以想到的解决方法是使用Firestore和Cloud Functions,在后端不可用时不断重试。
当后端不可用时,从前端将用户数据写入Firestore。然后使用Firebase Cloud函数不断尝试将数据写入外部数据库。成功后,您可以删除Firestore文档。
英文:
A workaround I can think of is using Firestore and Could Functions to keep retrying when your backend is down.
When your backend is down, write the user data to Firestore from your frontend. Then use a Firebase Cloud function to keep trying to write that data to your external dB. After succeeding, you can delete the Firestore document.
答案2
得分: 0
这实际上比预期的要简单得多。在后端,我有一个名为 /init
的端点,用于在后端创建用户并将其添加到 Firebase 用户的 ID 令牌结果中。然后在前端,我有一个身份验证守卫,确保如果用户的 ID 令牌结果中还没有后端 ID 设置,就会初始化用户与后端关联。
英文:
This is actually much simpler than expected. On the backend, I have an endpoint called /init
that creates the user on the backend and adds to backend user it to the Firebase user's id token result. Then on the frontend, I have an auth guard which makes sure that the user gets initialized with the backend if he doesn't already have the backend id set in the id token result.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论