0
votes

I am trying to push data to my database and I want to check if the pushed data's owner id is the same as the uid of the person pushing it. I get permission denied . I don't know how to write security rules for pushing data, and I can't find anything about it. The data structure looks like this:

Shops{
    "Shop1PushId" : {
        "ShopCredentials" : {
        "Owner" : "ownerUID"
        }
    }
    "Shop2PushId" : {
    ...
}

This is the object I am pushing.

{
    "ShopCredentials" : {
        "Owner" : "owner_id",
        "Another" : "another thing"
    }
}

This is my firebase rule:

"Shops" : {
  ".read" : true,
  ".write" : "newData.child('ShopCredentials').child('Owner').val() === auth.uid"
}

Code in android studio:

DatabaseReference shopsRef = database.getReference("Shops");
shopsRef.push().child("ShopCredentials").child("Owner").setValue(shopData.getShopOwner());
1

1 Answers

0
votes

Right now you're enforcing the rules on /Shops itself. But that is a list of shops. You're looking to enforce the rules on a specific shop, not on the list. To do that you add a so-called $ variable to the rules, which indicates that the rules below it apply to each child node:

"Shops" : {
  ".read" : true,
  "$shopid": {
    ".write" : "newData.child('ShopCredentials').child('Owner').val() === auth.uid"
  }
}

Now anyone can read all of the shops (even when they don't know the specific show ID), but someone can only write the shop if they know its specific ID and specify themselves as the owner of the new shop.

I'm not sure what you're exactly trying to secure here. If you are looking to bootstrap the process, so that people can only create new shops that have themselves as the owner, realize that with these rules anyone can still claim ownership of any shop they know the ID of. If you want to prevent that, and only want to allow claiming of ownership when the shop is created, use something like this:

"Shops" : {
  ".read" : true,
  "$shopid": {
    "ShopCredentials": {
      "Owner": {
        ".write" : "!data.exists() && newData.val() === auth.uid"
      }
    }
  }
}