Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 568
Vash Avatar asked Jul 31 '15 00:07

Vash


1 Answers

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.

like image 103
Rob DiMarco Avatar answered Nov 15 '22 22:11

Rob DiMarco