使用 js 模块化 Web sdk 创建之前测试文档是否存在时权限缺失或不足

问题描述 投票:0回答:1

使用Web模块化API(firebase js sdk 11.0.1以及之前的版本),当我在测试存在后调用setDoc时,我得到:

权限缺失或不足

export async function setYouTubePublication(publication: YouTubePublication) : Promise<void> {
    console.log("setYouTubePublication", publication);  
    const db = getFirestore();
    const ref = doc(db, "youtube_publications", publication.youtubeID);
    const snap = await getDoc(ref);
    if (snap.exists()) {
        throw new Error(`YouTube publication with ID ${publication.youtubeID} already exists`);
    }
    return setDoc( ref, publication );
}
rules_version = '2';

service cloud.firestore {
    match /databases/{database}/documents {
        match /youtube_publications/{document} {
            allow read: if request.auth != null && resource.data.owner == request.auth.token.dcid;
            allow create: if request.auth != null;
        }
    }
}

如果我删除存在测试,setDoc 将按其应有的方式工作:

export async function setYouTubePublication(publication: YouTubePublication) : Promise<void> {
    console.log("setYouTubePublication", publication);  
    const db = getFirestore();
    const ref = doc(db, "youtube_publications", publication.youtubeID);
    return setDoc( ref, publication );
}

有人知道我做错了什么或者是否有解决方法?好像有bug。

javascript firebase google-cloud-firestore
1个回答
0
投票

问题在于你的

read
规则:

allow read: if request.auth != null && resource.data.owner == request.auth.token.dcid;

如果文档不存在,则规则引擎无法确定

resource.data.owner
,因此会引发错误。评估规则时出现任何错误都意味着操作被拒绝。

如果您希望该操作起作用,请显式检查资源是否存在:

allow read: if request.auth != null &&
  (!exists(/databases/$(database)/documents/youtube_publications/$(document))
   || resource.data.owner == request.auth.token.dcid);
© www.soinside.com 2019 - 2024. All rights reserved.