且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Firebase 身份验证在用户注册过程中保存额外信息

更新时间:2023-12-05 17:45:40

这是每个 firebase 用户都必须处理的问题.一般是怎么解决的?正如其他用户指出的那样,通过将额外的用户信息添加到 Firestore 来解决这个问题.你能保证原子性吗?不,你不能,auth 和 db 是两个不同的系统,你可以将用户添加到 auth 并在回调中发现你不能将用户添加到 db,因为你没有互联网连接.人们做什么?一般都住它.

This is something that every firebase user has to deal with. How is generally solved? As other users point out, it is solved by adding the extra user information into Firestore. Can you guarantee that atomiticy? No, you can't, auth and db are two different systems, you can add the user to auth and in the callback find out you cannot add the user to db because you dont have internet connection for instance. What people do? Generally live with it.

如果保证原子性是您的应用程序的基础,您可以加倍努力并在 firebase 函数中实现您的身份验证.例如,这是一个两步登录的例子:

If it is fundamental for your application to guarantee atomiticy you can go an extra mile and implement your authentication in a firebase function. For instance, this is an example of a two step sign in:

import { Request, Response } from "express";
import * as admin from 'firebase-admin'

export async function create(req: Request, res: Response) {
   try {
       const { displayName, password, email, role } = req.body

       if (!displayName || !password || !email || !role) {
           return res.status(400).send({ message: 'Missing fields' })
       }

       const { uid } = await admin.auth().createUser({
           displayName,
           password,
           email
       })
       await admin.auth().setCustomUserClaims(uid, { role })

       return res.status(201).send({ uid })
   } catch (err) {
       return handleError(res, err)
   }
}

function handleError(res: Response, err: any) {
   return res.status(500).send({ message: `${err.code} - ${err.message}` });
}

如果出现问题,您可以添加从 auth 中删除用户.这至少可以保证您的回滚代码将在 Google 服务器中执行.

You could add the user removal from auth if something goes wrong. This guarantees at least that your rollback code will be executed in the Google servers.

此代码示例摘自 https://www.toptal.com/firebase/role-based-firebase-authentication