簡體   English   中英

CRUD 操作 React 的 Firestore 安全規則

[英]Firestore Security Rules for CRUD Operations React

我對 firebase 比較陌生,並且一直在使用它來集成 Firestore 和身份驗證與我正在開發的 ReactJS 應用程序。

我知道 collections 保存文檔,並且有效的文檔保存鍵值對。 我有一系列歌曲,其中包含以下字段:-

  1. 創建的時間戳

  2. 歌詞

  3. 歌名

我可以使用 firebase 身份驗證登錄用戶,當他們登錄並創建新歌曲時獲取用戶的 UID,使用文檔 ID 作為 UID 將條目輸入數據庫。

只有當我將規則設置為

match /{document=**} {allow read, write:}

當我將規則更改為:-

rules_version = '2';
service cloud.firestore {

  match /databases/{database}/documents {
  match /songs/{songID} {
     allow read:  if request.auth!=null;
     allow write: if isValid();
  }

  function isValid(){
     return request.resource.data.uid == request.auth.uid;
  }}}

運行時出現以下錯誤。

Unhandled Rejection (FirebaseError): Missing or insufficient permissions.

我只想確保登錄用戶可以閱讀、編寫和更新他/她自己的歌曲,除此之外什么都沒有。

1)我無法理解如何構建 firebase 規則來實現這一點並防止權限錯誤。

2)如果我使用文檔ID作為UID,即5首歌曲的相同文檔ID。 由於特定用戶的文檔 ID 相同,我如何能夠更新歌曲中的歌曲標題/歌詞?

我無法理解如何構建 firebase 規則來實現這一點並防止權限錯誤。

以下規則可以解決問題:

rules_version = '2';
service cloud.firestore {

  match /databases/{database}/documents {

    match /songs/{songID} {
       allow read:  if request.auth.uid == resource.data.uid;
       allow write: if isValid();
    }

    function isValid(){
       return request.resource.data.uid == request.auth.uid;
    }
  }
}

我建議您觀看此文檔頁面中嵌入的非常清晰的視頻: https://firebase.google.com/docs/firestore/security/get-started?authuser=0


如果我使用文檔 ID 作為 UID,即 5 首歌曲的相同文檔 ID。 由於特定用戶的文檔 ID 相同,我如何能夠更新歌曲中的歌曲標題/歌詞?

您不能對不同的 Firestore 文檔使用相同的文檔 ID。 根據定義,文檔 ID 必須是唯一的。 最好的辦法是讓 Firestore 生成一個文檔 ID(例如使用add()方法)並在文檔中添加作者uid ,就像您已經完成的那樣(因為您執行request.resource.data.uid )。

然后,您可以構建過濾與用戶uid對應的文檔的查詢。 例如:

var user = firebase.auth().currentUser;

var songsRef = db.collection("songs");
var mySongsQuery = songsRef.where("uid", "==", user.uid);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM