【问题标题】:Firestore denying permission to create/push collectionFirestore 拒绝创建/推送集合的权限
【发布时间】:2021-10-13 01:30:36
【问题描述】:

我是 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;
    }
  }
}

有人知道我该怎么做吗?

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore firebase-security


    【解决方案1】:

    首先,请仔细检查您的代码中是否包含 Firestore SDK。然后...您正在使用 RTDB 语法尝试将文档添加到 createUserRoles 中的 Firestore。您需要将其切换为 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/catch 承诺。

    【讨论】:

    • 谢谢乔,这很好!非常感谢!
    猜你喜欢
    • 2011-12-24
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2018-10-24
    • 2014-02-01
    • 1970-01-01
    • 2021-11-16
    相关资源
    最近更新 更多