我正试图在web项目中使用Firebase(使用NextJS(,但我的问题是:用户没有帐户,所以帐户自然是用createUserWithEmailAndPassword()
创建的。然而,我想在创建帐户后立即将数据存储在Firestore中。。。这就是问题所在。事实上,Firebase抛出了以下错误:
FirebaseError:[code=permission denied]:缺少或权限不足。
这是我的代码摘录:
import { useState } from "react";
import {
createUserWithEmailAndPassword,
getAuth,
} from "firebase/auth";
import {
collection,
getFirestore,
addDoc,
} from "firebase/firestore";
export const ConnectionPage = () => {
// the values of the inputs in the HTML content
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
// the function executed when the user clicks the register button
const submit = async (e) => {
e.preventDefault();
// create a new user with email and password
// and add the document in the "users" collection
try {
const userCredentials = await createUserWithEmailAndPassword(
getAuth(),
email,
password
);
const user = userCredentials.user;
const userInfo = {
uid: user.uid,
// ...and all kind of data
};
const collectionRef = collection(getFirestore(), "users");
// my problem starts here
// the following line will throw an error
// "[code=permission-denied]: Missing or insufficient permissions."
// whereas, according to the rules in Firestore, it should work
// because I just ask the user to be authenticated (`allow write, read: if request.auth != null`)
// and according to the documentation, `createUserWithEmailAndPassword` logs in the user.
const docRef = await addDoc(collectionRef, userInfo);
console.log(`New document with id '${docRef.id}' created successfully.`);
} catch (e) {
console.error("An error has occured during register, look:");
console.error(e.toString());
}
};
// returns a form
// with an email input
// and a password input
// and a button to register
};
以下是我在Firestore的规则:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow write, read: if request.auth != null;
}
}
}
请帮助我,我能找到的解决类似问题的唯一方法是在创建帐户后注销用户,然后立即登录。
我试过了:
promise语法(.then()
(中的- ,但问题与
async/await
相同 onAuthStateChanged()
,但同样的问题也出现了- 将规则更改为更复杂的东西(比如根据
request.auth.uid
测试用户的存在(也不起作用
当您只有:时
allow read;
这是一个完整的语句,意味着没有人可以读取数据。
如果您想对读取和写入应用相同的条件,请使用:
allow read, write: if request.auth != null;
在创建帐户时尝试使用身份验证状态观测器,而不是仅使用await
。根据我的经验,当前用户对象不会在创建帐户后立即设置,您必须等到身份验证状态观察器用非null用户对象触发后才能执行经过身份验证的查询。如果没有非null的currentUser,需要身份验证的Firestore查询将失败。
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
如果你觉得这是一个bug,那么我建议你在GitHub上提交它。
多亏了我在GitHub中与贡献者交谈,问题得到了解决。问题来自应用程序检查功能,该功能在9.6.0
版本之前不适用于Firestore。
解决方案是:
npm install firebase@9.6.0
默认情况下,npm install firebase
正在安装版本9.5.0
。
请注意,这个版本是最新的,如果你在2031年看到这个消息,那就完全没有用了。
感谢回答我的人:(