Firebase/Firestore - 如何为新用户创建新文档

时间:2020-12-23 21:17:29

标签: javascript firebase react-native google-cloud-firestore firebase-security

使用 Google SignIn 时,我希望 Firestore 为与我拥有的 user.uid 匹配的新用户创建用户/文档。我使用了 this post 中的 Firestore 规则。

编辑:但是,仍然出现此错误:

C:\Users\alobre\Documents\Programmieren\BountyHunter\node_modules\react-devtools-core\dist\backend.js:32 Possible Unhandled Promise Rejection (id: 1):
Error: [firestore/permission-denied] The caller does not have permission to execute the specified operation.
NativeFirebaseError: [firestore/permission-denied] The caller does not have permission to execute the specified operation.
    at FirestoreCollectionReference.get (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:133094:39)
    at _callee$ (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:197066:93)
    at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24879:19)
    at Generator.invoke [as _invoke] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25052:24)
    at Generator.next (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24922:23)
    at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24879:19)
    at invoke (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24952:22)
    at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:24982:13
    at tryCallTwo (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26948:7)

这是我的代码: 添加用户

export default function addUser(user){
  console.log(firestore())
  firestore()
   .collection('users')
   .doc(user.uid)
   .set({
     user
   })
   .then(() => {
     console.log('User added!');
   }); 
 }

按下登录按钮时调用

async function onGoogleButtonPress() {
  GoogleSignin.signIn()
  .then((data) => {
    const credential = auth.GoogleAuthProvider.credential(data.idToken, data.accessToken);
    return auth().signInWithCredential(credential);
  })
  .then((user) => {
    addUser(user)
  })
  .catch((error) => {
    const { code, message } = error;
  });
}

我的 Firestore 规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
// Allow users to create a document for themselves in the users collection
    match /users/{document=**} {
      allow create: if request.resource.id == request.auth.uid &&
        !("admin" in request.resource.data);
    }
    
    // Allow users to read, write, update documents that have the same ID as their user id
    match /users/{userId} {   
        // Allow users to read their own profile (doc id same as user id)
      allow read: if request.auth.uid == userId;
      
      // Allow users to write / update their own profile as long as no "admin"
      // field is trying to be added or created - unless they are already an admin
      allow write, update: if request.auth.uid == userId &&
        (
          !("admin" in request.resource.data) ||
          get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true // allow admin to update their own profile
        )
      }
  }
}

1 个答案:

答案 0 :(得分:1)

已解决: Firestore 规则是正确的。但是我收到一个错误,提示权限被拒绝。 原因:

match /users/{document=**} {
  allow create: if request.resource.id == request.auth.uid &&
    !("admin" in request.resource.data);
}

request.resource.id 与请求 auth.uid 不匹配 我试图用 GoogleSignin 模块的 uid 创建一个文档(它甚至没有 uid 但有一个 id)。

正确的做法是:

.then(
  Post(auth().currentUser)
)

Firestore 需要这个 auth().currentUser.uid 而我给的 GoogleSignin.signIn().uid 与 request.auth.uid 不匹配