How to allow firebase user to only access documents that they created

旧巷老猫 提交于 2021-01-29 12:26:10

问题


This, to me, is the most basic authentication scheme for user-generated content, given a collection called "posts":

  1. Allow any authenticated user to insert into "posts" collection
  2. Allow the user who inserted the document into collection "posts", to read, update, and destroy the document, and deny all others
  3. Allow the user to list all documents in collection "posts" if they are the one who created the documents originally

All examples I've found so far seem to rely on the document ID being the same as the user's id, which would only work for user's "profile" data (again, all the examples seem to be for this single limited scenario).

It doesn't seem that there is any sort of metadata for who the authenticated user was when a document was created, so it seems i must store the ID on the doc myself, but I haven't been able to get past this point and create a working example. Also, this opens up the opportunity for user's to create documents as other users, since the user ID is set by the client.

I feel like I am missing something fundamental here since this has to be the most basic scenario but have not yet found any concise examples for doing this.


回答1:


This answer is from this github gist. Basically, in the document collection posts there is a field called uid and it checks if it matches the users uid.

// Checks auth uid equals database node uid
// In other words, the User can only access their own data

{
  "rules": {
    "posts": {
       "$uid": {
         ".read": "$uid === auth.uid",
         ".write": "$uid === auth.uid"
       }
     }
   }
}

-- Edit --

DSL rules

match /Posts/{document=**}{
    allow read : if uid == request.auth.uid;
    allow write: if uid == request.auth.uid;
}


来源:https://stackoverflow.com/questions/58249305/how-to-allow-firebase-user-to-only-access-documents-that-they-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!