0

I saw in several places that the way to prevent create and delete was with data.exists() && newData.exists(). But when I implement them in these rules, I can still create and delete to my liking when I'm logged in. What am I doing wrong? My goal is to let authenticated users update, but not create or delete.

"rules": {
    "listings": {
      ".read": true,
      ".write": "data.exists() && newData.exists() && auth != null",
    },
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
tclarkMEOW
  • 131
  • 1
  • 12

1 Answers1

1

My guess is that you want to allow the user to update a specific listing, and not all listings at once.

In that case you should define the .write rule on each specific listing:

"rules": {
    "listings": {
      ".read": true,
      "$listingid": {
        ".write": "data.exists() && newData.exists() && auth != null",
      }
    },
}

So with this, a user can update any existing listing, but not all listings at one.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Oh my gosh. Either you're a genius or I'm dumb. That works exactly how I want. I was in the middle of an edit when I saw this. Why can't we just set the write conditions on the whole thing? I don't know why these security rules are such a struggle for me. – tclarkMEOW Jan 26 '21 at 21:27
  • You *can* set permissions on "the whole thing", but that means those permissions apply to that whole thing. So if you set permissions on `listings` then `data` is the data for all listings before the write, and `newData` is the data for all listings after the write (if it succeeds). And most likely in your code (which is what I asked for in a comment) you are just writing a single listing, so both `data` and `newData` will exist, since there are other listings than the one you're updating. – Frank van Puffelen Jan 26 '21 at 21:31
  • 1
    Ok I think I understand. It's looking at the data as a WHOLE. Whereas, with your way (the way that works how I want), it's comparing the specific listing that it's on. Otherwise it says Yeah there was data before, there's data now! True! Light bulb. Thanks. – tclarkMEOW Jan 26 '21 at 21:34
  • You're welcome. This one is indeed tricky to initially grasp, and we've found it hard to explain better than this in a general way: https://firebase.google.com/docs/database/security/core-syntax#wildcard_capture_variables – Frank van Puffelen Jan 26 '21 at 21:53