如何在firestore中创建新的用户文档

Nod*_*rov 3 javascript firebase firebase-security google-cloud-firestore

我正在尝试实现这个逻辑,当用户成功注册时,应用程序会id=user.email在 firestore 中创建一个文档。为此,我在 firestore 中创建了以下安全规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if request.auth != null;
    }
    match /users/{userId}{
        allow read: if request.auth != null;
        allow write: if request.auth.token.email == userId;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

以及我的应用程序中的以下代码:

const { email, password, name, lastName } = value;

firebase
  .auth()
  .createUserWithEmailAndPassword(email, password)
  .then(() => {
        firestore.collection('users').doc(email).set({
          name, lastName
        })
        .then(function(docRef) {
          console.log("Document written with ID: ", docRef.id);
        })
        .catch(function(error) {
          console.error("Error adding document: ", error);
        });
        this.props.navigation.navigate('Main')
      })
  .catch(error => alert(error))
Run Code Online (Sandbox Code Playgroud)

当我运行我的应用程序时,出现以下错误:

Error adding document: , [FirebaseError: Missing or insufficient permissions.]
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 7

使用用户的电子邮件地址作为唯一标识符并不是一个好主意,因为它可能会随着时间的推移而发生变化。最好使用 Firebase 身份验证分配的唯一用户 ID (uid)。

规则:

match /users/{userId} {
    allow read: if request.auth != null;
    allow write: if request.auth.uid == userId;
}
Run Code Online (Sandbox Code Playgroud)

代码:

firebase
  .auth()
  .createUserWithEmailAndPassword(email, password)
  .then(userCredential => {
        firestore.collection('users').doc(userCredential.user.uid).set({
          name, lastName
        })
Run Code Online (Sandbox Code Playgroud)

这种情况更为常见,可以更轻松地编写安全规则,并且可以抵抗电子邮件更改。