javascript - 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;
}
}
}
有谁知道我该怎么做?
解决方案
首先,仔细检查您的代码中是否包含 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/catch
promises。
推荐阅读
- cryptography - 验证 PE 文件的数字签名
- sql - 在基于两列不等式进行过滤时,SQL 中 WHERE 子句的底层到底发生了什么
- javascript - Object Promise,不可能得到值
- android - 在存储库层中映射域对象和 DTO
- .net - 如何模拟 3rd 方库的工厂方法的返回类型?
- javascript - 在数组中,从每个对象中的数组中删除该项目出现的项目
- mysql - 如何在 Spring Boot JPA 应用程序中打印带有值的 sql 语句
- twilio - 语音邮件的不同 Twiml
- c - MinGW 错误“仅支持 Win32 目标”
- python - 有没有办法检查列表项是否是列表中的唯一项?