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

Jer*_*yal 1 html authentication firebase firebase-authentication google-cloud-firestore

我正在构建一个网站,我在其中集成了用于登录/注册站点用户的Firebase 身份验证

用户可以通过电子邮件密码或移动 OTP 方法登录/注册。我正在使用官方 firebase js Auth UI Widget: firebaseui-web进行此身份验证过程。

在注册时,我还想捕获其他用户详细信息,例如全名、性别、年龄等。

为此,我在网上找到了两种方法:

  1. 成功注册后,将额外信息存储在 firestore 中。

    这种方法的问题是我想成为一个原子事务。手段,要么所有的额外的信息应在注册过程中被储存注册过程中不应该会成功。我不确定如何实现这个流程,或者甚至根本不可能。

  2. 使用 JSON.stringify/JSON.parse 方法在 firebase auth 对象字段中存储额外信息,如 displayName、photoURL。我正在使用他们的身份验证 UI 小部件,但不确定如何在电子邮件或移动 OTP 注册期间嵌入此信息。

那么,如何在注册过程中保存用户的额外信息?有什么不同的方法吗?

网站托管在 firebase 托管上。站点使用 firestore 来存储用户的任何其他数据,因为 firebase auth 不提供此功能。我还为一些基本的 CRUD 操作实现了 firebase 云函数(Typescript、node.js)。所以简而言之,一个完整的火力环境。

小智 5

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.

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}` });
}
Run Code Online (Sandbox Code Playgroud)

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.

This code example was extracted from https://www.toptal.com/firebase/role-based-firebase-authentication