React应用中Firebase注册后写入Firestore权限不足问题求助
解决Firebase注册后写入Firestore权限不足问题
问题根源
你的代码中createUserWithEmailAndPassword是异步操作,但你直接同步调用了setDoc。此时Firebase Auth还未完成用户认证状态的更新,导致Firestore安全规则检测到request.auth为null,触发"权限不足"的错误。
解决方案:等待注册异步操作完成后再写入数据
必须确保用户注册完成、Auth状态更新后,再执行Firestore写入操作。可以通过以下两种方式实现:
方式1:使用async/await(推荐)
async function signUp(email, password) { try { // 等待注册流程完成,获取用户认证信息 const userCredential = await createUserWithEmailAndPassword(auth, email, password); // 此时用户已完成认证,Auth状态已更新 await setDoc(doc(db, 'users', email), { savedShows: [] }); console.log("用户注册及数据写入成功"); } catch (error) { console.error("操作失败:", error.message); } }
方式2:使用.then()链式调用
function signUp(email, password) { createUserWithEmailAndPassword(auth, email, password) .then(() => { // 注册成功后再执行Firestore写入 return setDoc(doc(db, 'users', email), { savedShows: [] }); }) .then(() => { console.log("用户注册及数据写入成功"); }) .catch(error => { console.error("操作失败:", error.message); }); }
额外建议:使用用户UID作为文档ID(更安全)
目前你使用邮箱作为Firestore文档ID,虽然可行,但用户邮箱可能会变更。推荐使用Firebase用户的唯一UID作为文档ID,避免后续因邮箱修改导致的数据关联问题:
修改后的代码示例:
async function signUp(email, password) { try { const userCredential = await createUserWithEmailAndPassword(auth, email, password); const user = userCredential.user; // 使用用户UID作为文档ID await setDoc(doc(db, 'users', user.uid), { email: email, savedShows: [] }); } catch (error) { console.error("操作失败:", error.message); } }
对应的Firestore规则需调整为:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow create: if request.auth != null && request.auth.uid == userId; allow read, write: if request.auth != null && request.auth.uid == userId; } } }
内容的提问来源于stack exchange,提问作者hoadesign
相关产品推荐
相关产品推荐

