【问题标题】:Firebase Document for each user?每个用户的 Firebase 文档?
【发布时间】:2018-10-09 17:20:34
【问题描述】:

我想知道如何在每个用户创建帐户时为他们制作一个文档(使用 Firebase Web)。我启用了 Firebase 身份验证并正常工作,然后我希望每个用户在 Cloud Firestore 中的一个名为 users 的集合中都有一个文档。如何获取 UID,然后为每个用户自动创建一个文档? (我这样做是为了可以将日历事件保存到文档中的数组字段中,但我需要一个文档供用户开始使用)。我知道并且知道如何为访问制定安全规则,我只是不知道如何首先制作文档。 谢谢!

【问题讨论】:

标签: javascript firebase google-cloud-firestore


【解决方案1】:

虽然正如 Renaud 和 guillefd 建议的那样,通过 Cloud Functions 创建用户个人资料文档是绝对可行的,但也可以考虑直接从您的应用程序代码中创建该文档。该方法非常相似,例如如果您使用电子邮件+密码登录:

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(function(user) {
    // get user data from the auth trigger
    const userUid = user.uid; // The UID of the user.
    const email = user.email; // The email of the user.
    const displayName = user.displayName; // The display name of the user.

    // set account  doc  
    const account = {
      useruid: userUid,
      calendarEvents: []
    }
    firebase.firestore().collection('accounts').doc(userUid).set(account); 
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
  });

除了直接从 Web 应用程序运行之外,此代码还使用用户的 UID 作为键创建文档,这使得后续查找更加简单。

【讨论】:

  • 我想这需要用户有权在帐户集合中创建文档?
  • @holmberd 是的,这可以处理它:match /accounts/{uid} {allow read, write: if uid == request.auth.uid;}
【解决方案2】:

您必须设置由 onCreate() Auth trigger 触发的 firebase 函数。
1. 创建函数触发器
2.获取用户创建的数据
3.设置账户数据。
4. 将账户数据添加到集合中。

函数/index.js

// Firebase function 

exports.createAccountDocument = functions.auth.user().onCreate((user) => {
  // get user data from the auth trigger
  const userUid = user.uid; // The UID of the user.
  //const email = user.email; // The email of the user.
  //const displayName = user.displayName; // The display name of the user.

  // set account  doc  
  const account = {
    useruid: userUid,
    calendarEvents: []
  }
  // write new doc to collection
  return admin.firestore().collection('accounts').add(account); 
});

【讨论】:

    【解决方案3】:

    如果您使用Firebase UI 来简化您的生活,您可以将用户文档添加到 Firestore 中的“/users”集合中当该用户首先 在 UI 配置中使用 signInSuccessWithAuthResult 中的 authResult.additionalUserInfo.isNewUser 进行注册。

    我在我的项目中做这样的事情:

    let uiConfig = {
    ...
      callbacks: {
        signInSuccessWithAuthResult: (authResult) => {
          // this is a new user, add them to the firestore users collection!
          if (authResult.additionalUserInfo.isNewUser) {
            db.collection("users")
              .doc(authResult.user.uid)
              .set({
                displayName: authResult.user.displayName,
                photoURL: authResult.user.photoURL,
                createdAt: firebase.firestore.FieldValue.serverTimestamp(),
              })
              .then(() => {
                console.log("User document successfully written!");
              })
              .catch((error) => {
                console.error("Error writing user document: ", error);
              });
          }
          return false;
        },
      },
    ...
    }
    ...
    ui.start("#firebaseui-auth-container", uiConfig);
    

    signInSuccessWithAuthResult 为您提供 authResultredirectUrl

    来自Firebase UI Web Github README

    // ...
    signInSuccessWithAuthResult: function(authResult, redirectUrl) {
      // If a user signed in with email link, ?showPromo=1234 can be obtained from
      // window.location.href.
      // ...
      return false;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-09
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 2019-07-17
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多