Firebase user read all, write new, but only modify his own data

无人久伴 提交于 2019-12-08 17:41:56

问题


I have the next scenario on Firebase:

There are 2 things, Users and events.

I would like the Users to be able to create new Events, see all the existing events but be only able to modify only the events that were created by them.

Meaning that UserOne created EventOne, can see EventOne and EventTwo, but can only modify EventOne.

My structure is as follows:

-events
 -eventOne
    endTime: 
    id: 
    name: 
    providerId: 
    startTime: 
    userId: 
 -eventTwo
    endTime: 
    id: 
    name: 
    providerId:  
    startTime: 
    userId: 
-users
    -userOne
    -userTwo

And my current rules are pretty much the default ones:

{
  "rules": {
    "users": {
      "$uid": {
        // grants write access to the owner of this user account whose uid must exactly match the key ($uid)
        ".write": "auth !== null && auth.uid === $uid",
        // grants read access to any user who is logged in with an email and password
        ".read": "auth != null && auth.uid == $uid"
      }
    },
     "events": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  }
}

Thanks in advance.


回答1:


To ensure that all users can see all events, you can set the read-rule for events to either be true or auth != null, using the latter if you want to require that readers are at least authenticated.

To ensure that events can only be modified by their creator, record the original author alongside the event and validate it using auth.uid.

{
  "rules": {
    "events": {
      "$eventid": {
        ".read": "auth != null",
        ".write": "auth != null && (!data.exists() || data.child('author').val() === auth.uid) && newData.hasChild('author')",
        "author": {
          ".write": "newData.val() === auth.uid"
        }
      }
    }
  }
}

Above, we use !data.exists() to check whether or not there is an existing event at this location. If no event exists, anyone can add one at this location. Next, data.child('author').val() === auth.uid ensures that if an event exists, only the author can modify it.



来源:https://stackoverflow.com/questions/31736252/firebase-user-read-all-write-new-but-only-modify-his-own-data

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