Pregunta

I'm having an issue setting my Security rules properly, specifically reading the post data.

The data hierarchy goes:

posts : {
    0 : {
        title: "Post One",
        userId: 6
    }
},
users : {
    6 : {
        name: "My Name"
    }
}

And my rules are:

{
  "rules": {
    "posts" : {
      "$post": {
         ".read":"data.child('userId').val() == auth.id",
         ".write":"newData.child('userId').val() == auth.id"
      }
    },
    "users":{
      "$user": {
        ".read":"auth.id == $user",
        ".write":"auth.id == $user"
      }
    }
  }
}

I know that the "auth.id" is 6, because it's pulling the rules correctly for my user info. If I change the rules to pull the number statically, it works:

      "$post": {
         ".read":"data.child('userId').val() == 6",
         ".write":"newData.child('userId').val() == auth.id"
      }

but using auth.id does not. Is there something I'm missing?

¿Fue útil?

Solución

One thing to keep in mind is that security rules are type-safe. In particular, In the rules, "6" != 6 (since one is a string and one is a number). So perhaps your auth.id is "6" (as a string), but your userId is 6 as a number?

If that's the case, one potential fix would be changing your rule expression to something like:

data.child('userId').val() + '' == auth.id

which will force userId to be a string. Alternatively, you could change your data to make sure userId is always stored as a string.

Otros consejos

You haven't included the code you're using to look up this data--probably where the error is--or the error you are receiving; those would help quite a bit.

Your rules should work fine, assuming you are attempting to read a single post at a time, and assuming your authentication is set up correctly.

A quick guess would be that you're trying to read the entire "posts" path, and using security rules to filter your posts. But security rules are essentially atomic. If you try to read "posts", and one of the posts has a rule that prevents read, the entire operation is going to fail.

Instead, you need to segment the posts into paths where all the data can be read by the authenticated user, then you can apply security rules accordingly.

One thing that will help immensely is to test your security rules by going into your Forge and using the "simulator". You can log in as any user, then try a read/write, and see exactly which security rules is failing and why.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top