2017-10-05 141 views
4

對於Firebase實時數據庫的安全規則,公共和私有數據可以使用如下規則存在於同一棵樹中。Firestore安全規則

但是,當使用Firestore時,似乎並沒有使我們能夠做同樣的事情,因爲我們可以檢索的數據的查找只在收集或文檔下。 當在同一文檔中定義公共和私人數據並獲取數據(集合/文檔)時,如果我們不是所有者,我們會發現私人數據的權限不足。

當使用RTDB時,我們可以獲取'users/{userId}/publicInfo'的數據,因爲我們對集合/文檔沒有任何想法。

有沒有辦法用Firestore來做到這一點?否則,我們應該分開收集公共/​​私人收藏?

// rule of Firebase Realtime Database 
"users": { 
    "$user_id": { 
     ".read": "auth.uid === $user_id", 
     ".write": "auth.uid === $user_id", 

     "private": { 
      ".read": "auth.uid === $user_id" // --- private data 
     } 

     "public": { 
      ".read": "auth !== null";   // --- public data 
     } 
    } 
} 

// Firestore 
service cloud.firestore { 
    match /databases/{database}/documents { 
    match /users/{userId} { 

     match /{private=**} { 
     allow read, write: if request.auth == userId; 
     } 

     match /{public=**} { 
     allow read, write: if request.auth != null; 
     } 
    } 
    } 
} 

回答

8

因此,您不能爲單獨的文檔部分分別制定安全規則。你可以閱讀整個文檔,或者你不能。

這就是說,如果你想給你的用戶ID文件一個包含公共和私人文檔的「公共」和「私人」子集合,這是你完全可以做的事情,而不是你現在設置的方式建立你的安全規則。

你所寫的match /{private=**}位並不意味着「匹配任何被稱爲」私人「的子集合。這意味着,「匹配任何子集合,無論如何,然後將其分配給名爲private的變量」。文檔中的「Recursive matching with wildcards」部分更詳細地介紹了這一點。

此外,您需要參考request.auth.uid以獲取用戶的ID。

所以,你可能需要更多的東西是這樣的:

// Firestore 
service cloud.firestore { 
    match /databases/{database}/documents { 
    match /users/{userId} { 
     // You'll probably want to add security rules around the user document 
     // itself. For now, though, let's look at our subcollections: 

     match /private/{anything=**} { 
     // Only the user can read documents in their private collection 
     allow read, write: if request.auth.uid == userId; 
     } 

     match /public/{anything=**} { 
     // Anybody can read documents here, as long as they're signed in 
     allow read, write: if request.auth != null; 
     } 
    } 
    } 
} 
+0

非常感謝。 Understood Firestore使我們不會將這些類型(公/私)數據放在同一個文檔中。正如你所說,可能的解決方案是有子收集,但這強制我們有一個文件的關鍵,這是不需要這種情況;例如/用戶/ {uidxx} /私人/ {uidyyy} /名字等,即使同一個uid是允許的。從集合中檢索數據時應注意,子集合的數據不包括在內,不是。 –

+0

請記住,您也可以在創建新文檔時指定密鑰本身。所以你可以有/用戶/ {uidxx}/private_data /私人/名字,這將工作得很好。此外,可能爲您的公共數據設置單獨的收集可能不是必要的 - 您可以將其保留在父文檔中。 –

+0

好的。再次感謝! –