首页 > 解决方案 > Firestore 拒绝创建/推送集合的权限

问题描述

我是 firebase / firestore 的新手,我正在尝试在登录和验证用户时、在客户端和使用 React 时创建一个新集合。我在这里阅读了其他几篇文章,并将数据库规则设置为 true 进行读取和写入,但是,我一直在 Firestore 数据库上收到错误,而如果我初始化实时数据库,它可以完美运行。另外,我可以获取和读取数据,但不能写入。

我的代码很简单:

    export default function Login() {
  const [isAuthenticated, setAuthenticate] = useState(false);
  const [newEditor, setNewEditor] = useState("");
  const uiConfig = {
    signInFlow: "popup",
    signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
    callbacks: {
      signInSuccessWithAuthResult: (user) => {
        console.log("success");
        createUserRoles(newEditor);
      },
    },
  };

  useEffect(() => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        if (user.email.split("@")[1] === "something.com") {
          setAuthenticate(!!user);
          setNewEditor(user.email);
          console.log(newEditor);
        } else {
          console.log("not allowed");
        }
      }
    });
  });

  const createUserRoles = (user) => {
    //on login the user will be added to editors collection with default value of reviewer
    console.log("hello from createeee");
    const editorsRef = firebase.database().ref("editors");
    const editor = {
      email: "user.email",
      role: "reviewer",
      lastSession: Date.now(),
    };
    editorsRef.push(editor);
  };

  return (
.....

我的规则是这样设置的:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if true;
      allow write: if true;
    }
  }
}

有谁知道我该怎么做?

标签: javascriptreactjsfirebasegoogle-cloud-firestorefirebase-security

解决方案


首先,仔细检查您的代码中是否包含 Firestore SDK。然后...您正在使用 RTDB 语法尝试将文档添加到createUserRoles. 您需要将其切换为 Firestore 的语法:

const createUserRoles = async (user) => {
    //on login the user will be added to editors collection with default value of reviewer
    console.log("hello from createeee");
    // This is RTDB syntax for a ref
    // const editorsRef = firebase.database().ref("editors");
    // Try this instead
    const editorsRef = firebase.firestore().collection("editors");

    const editor = {
      email: "user.email",
      role: "reviewer",
      lastSession: Date.now(),
    };

    // This is how you add an item to RTDB
    // editorsRef.push(editor);
    // This is the Firestore way to create a new record with a random, unique document id
    await editorsRef.add(editor);
  };

Firestore 的读写(就像 RTDB 一样)并不是异步的,所以你需要使用async/await(就像我添加的那样)或then/catchpromises。


推荐阅读