I am trying to create a text editor app using firebase that allows users to create documents, but they can also nest a new document inside an existing document (when editing a document, they would be able to click on a button that would add a new document in the database and insert a link in the editor that redirects towards this page):
A user would be able to share a document with other users, but then they should have access to all the nested documents as well. So now I am wondering how to write the security rules to do that.
I think the best way to structure the realtime database would be to store all documents at the root, and then add a parentDocument
or path
property to each document:
{
"documents": {
"doc-1": {
"title":"Lorem ipsum",
"content": "...",
"path":"/",
"owner":"user-1",
"canAccess":{
"user-3":true
}
},
"doc-2": {
"title":"Dolor sit",
"content": "...",
"path":"/doc-1/",
"owner": "user-1"
"canAccess": {
"user-2":true
}
}
},
"users": {
"user-1": { ... },
"user-2": { ... },
"user-3": { ... }
}
}
↑ In the example below,
- doc-2 is nested inside doc-1
- user-1 can access both doc-1 and doc-2
- user-2 can access doc-2 only
- user-3 can access both doc-1 and doc-2
But now I do not know how to manage the security rules, because to check if a user has access to a specific document, I guess it would need to go through each of its parents (using its path
or parentDocument
prop). Perhaps I could also specify the canAccess
prop on each document, but then I would have to update each nested document whenever a parent's canAccess
prop is updated...
Any help would be greatly appreciated
CodePudding user response:
In the Firebase Realtime Database model permission automatically cascades downwards. This means that once you grant a user (read or write) permission on a specific path, they can also access all data under that path. You can never revoke the permission at a lower level anymore.
So your requirement actually matches really nicely with this model, and I'd recommend just trying to implement it and reporting back if you run into problems.