You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在谷歌Auth登录后在Firebase Firestore创建用户记录

实现谷歌授权登录时自动创建Firestore用户记录

你的思路方向完全正确!把邮箱注册时创建Firestore用户记录的逻辑移植到谷歌授权流程里,核心就是在signInWithCredential的成功回调中对接Firestore操作,你已经走对了路子。这里给你几个优化点和完整的实现方案:

关键优化建议

  • 避免重复覆盖用户数据:如果用户已经通过谷歌登录过,单纯的set()会覆盖掉之前的bio或其他字段。建议使用set({...}, {merge: true}),这样只会更新指定字段,保留已存在的其他数据。
  • 利用谷歌用户的默认信息:可以从谷歌授权返回的用户对象中获取昵称、邮箱等信息,作为bio的默认值,比固定的testing更实用。
  • 区分首次登录与重复登录:通过additionalUserInfo.isNewUser判断用户是否是首次登录,只在首次登录时创建记录,减少不必要的Firestore请求。
  • 完善错误处理:不要只捕获认证错误,也要处理Firestore操作可能出现的异常。

修改后的完整代码

/**
 * Start the auth flow and authorises to Firebase.
 * @param{boolean} interactive True if the OAuth flow should request with an interactive mode.
 */
function startAuth(interactive) {
  // Request an OAuth token from the Chrome Identity API.
  chrome.identity.getAuthToken({interactive: !!interactive}, function(token) {
    if (chrome.runtime.lastError && !interactive) {
      console.log('It was not possible to get a token programmatically.');
    } else if(chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError);
    } else if (token) {
      // Authorize Firebase with the OAuth Access Token.
      var credential = firebase.auth.GoogleAuthProvider.credential(null, token);
      firebase.auth().signInWithCredential(credential)
        .then(result => {
          // 仅在用户首次登录时创建Firestore记录
          if (result.additionalUserInfo.isNewUser) {
            const user = result.user;
            // 使用谷歌用户的昵称作为默认bio,也可以扩展其他字段
            return db.collection('users').doc(user.uid).set({
              bio: user.displayName || 'No bio provided',
              email: user.email,
              createdAt: firebase.firestore.FieldValue.serverTimestamp()
            }, { merge: true }); // 合并模式,避免覆盖已有数据
          }
          // 如果是老用户,直接返回,不执行Firestore操作
          return Promise.resolve();
        })
        .then(() => {
          // 登录成功后的其他操作,比如跳转页面、更新UI等
          console.log('登录完成,用户记录已同步');
        })
        .catch(function(error) {
          // 处理认证或Firestore操作的错误
          if (error.code === 'auth/invalid-credential') {
            chrome.identity.removeCachedAuthToken({token: token}, function() {
              startAuth(interactive);
            });
          } else {
            console.error('登录或用户记录创建失败:', error);
          }
        });
    } else {
      console.error('The OAuth Token was null');
    }
  });
}

代码说明

  1. 首次登录判断:result.additionalUserInfo.isNewUser是Firebase Auth提供的属性,能准确识别用户是否是第一次通过该方式登录。
  2. 合并写入模式:{ merge: true }确保如果用户后续更新了bio,下次登录不会被默认值覆盖。
  3. 扩展用户字段:除了bio,还可以加入email、createdAt等实用字段,丰富用户记录。
  4. 完整错误处理:统一的catch块处理认证和Firestore的所有错误,避免遗漏异常。

这样修改后,你的谷歌授权登录流程就能和邮箱注册流程保持一致,自动为新用户创建Firestore记录,同时兼顾老用户的数据安全。

内容的提问来源于stack exchange,提问作者bbowesbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:32:54