Accessing object property in Firebase Realtime Database ruleset - firebase

I store data about trips in a Firebase Realtime Database. I have defined some user groups. I want only users from group "vips" to read trips that have freePlaces == 0 and all the others to read the remaining trips.
I tried to set such access rules:
{
"rules": {
"trips":{
"$trip":{
".read": "root.child('users').child('vips').child(auth.uid).exists() || $trip.child('freePlaces') > 0"
}
}
}
}
but Firebase tells me $trip has no method/property 'child'.
I tried to do it in a different way
{
"rules": {
"trips":{
"$trip":{
".read": "root.child('users').child('vips').child(auth.uid).exists() || root.child('trips').child($trip).child('freePlaces') > 0"
}
}
}
}
but Firebase says Invalid > expression: left operand must be a number or string.
What went wrong?

I recommend playing close attention to the type of each expression in your rules:
$trip is a string, which explains why you can't call .child on it. If you want to get a child of the node, you can just do: data.child('freePlaces').
root.child('trips').child($trip).child('freePlaces') is a location in the database, which can't be compared with >. If you want the value of the node, use .val().
So combining these, your first snippet should be:
data.child('freePlaces').val() > 0

Related

How does .indexOn works with users and unique keys?

I am confused with index rules in firebase. I have this database and I wanted to extract distance_traveled in battery_and_cables. The thing is, 1 is something like a userID set by the user itself so that will vary.
I used this code in pyrebase to extract the distance_traveled
db.child("mileage_maintenance").order_by_child("distance_traveled").get()
but I get
Index not defined, add ".indexOn": "distance_traveled", for path "/mileage_maintenance", to the rules
This is my database:
Any my rules:
{
"rules": {
".read": true,
".write": true,
"mileage_maintenance": {
"battery_and_cables":{
".indexOn": ["distance_traveled"]
}
},
}
}
Is there any way you can go through the 1 and the push key to acquire the distance_traveled?
Firebase Realtime Database queries work on a flat list of the nodes under the location where you run the query. So in your case, the query considers the direct children of the mileage_maintenance node (which is just the node 1 in the screenshot).
You can have wildcards in your rules, like in your case:
{
"rules": {
".read": true,
".write": true,
"mileage_maintenance": {
"$id": {
"battery_and_cables":{
".indexOn": ["distance_traveled"]
}
}
}
}
}
As you can see, I added a $id level here for the 1 node. That now means that you have an index defined on each /mileage_maintenance/$id/battery_and_cables node for the distance_traveled property of each child node under that.
So with this index, you can query a specific /mileage_maintenance/$id/battery_and_cables path for the distance_traveled values. But you can't run a query on just /mileage_maintenance for all distance_traveled values under it.
If you need such a query, you will need to modify/augment your data model to allow it. For example, by introducing a flat list of distance_traveled nodes that you can then query:
"distance_traveled": {
"1000000": "1/battery_and_cables/-M01CT...1hMj"
}
Or
"distance_traveled": {
"1~battery_and_cables~-M01CT...1hMj": 1000000
}
Where the ~ in that last model is just a separate for the segments in that key, since / isn't allowed.
Also see:
Firebase Query Double Nested
Firebase query if child of child contains a value

Firebase Rules: Read restriction for dynamic child nodes

I'm trying to implement a Firebase rules read restriction in a data model that has a few nested dynamic child nodes.
I have the following data model:
/groupMessages/<groupId>/<messageId>/
{
"senderId": "<senderId>",
"recipientId": "<recipientId>",
"body": "..."
}
groupId, messageId, senderId and recipientId are dynamic ids. I would like to attach a listener to the /groudId node to listen to new messages. At the same time I only want users to read the message where the senderId or recipientId matches a corresponding auth.token value.
Due to Firebase cascading rules, if I allow the read at the groupId level without restrictions, I can't deny them on the message level.
{
"rules": {
"groupMessages"
"$groupId": {
".read": "auth != null"
}
}
}
}
I also haven't found a way to restrict the read rule on the groupId level to check for sender/recipientId of a message.
Any suggestions greatly appreciated.
As you've found, security rules cannot be used to filter data. But they can be used to restrict what queries can be performed on the data.
For example, you can query for all messages where the current user is the sender with:
var query = ref.child("groupMessages").child(groupId).orderByChild("senderId").equalTo(uid);
And you can secure access to the group's messages to only allow this query with:
{
"rules": {
"groupMessages": {
"$groupId": {
".read": "auth.uid != null &&
query.orderByChild == 'senderId' &&
query.equalTo == auth.uid"
}
}
}
}
The query and rules now exactly match, so the security rules will allow the query, while they'd reject a broader read operation. For more on this, see query based rules in the Firebase documentation
You'll note that this only works for a single field. Firebase Database queries can only filter on a single field. While there are workarounds by combining multiple values into a single property, I don't think those apply to your scenario, since they only work for AND queries, where you seem to want an OR.
You also seem to want to query on /groupMessages instead of on messages for a specific group. That also isn't possible: Firebase Database orders/filters on a property that is at a fixed path under each child of the node where you run the query. You cannot query across two dynamic levels, as you seem to be trying. For more on this see: Firebase Query Double Nested and Firebase query if child of child contains a value.
The common solution for your problem is to create a list of IDs for each user, which contains just the IDs of all messages (and/or the groups) they have access to.
userGroups: {
uid1: {
groupId1: true,
groupId2: true
},
uid2: {
groupId2: true,
groupId3: true
}
}
With this additional data structure (which you can much more easily secure), each user can simply read the groups they have access to, and your code then reads/queries the messages in each group. If necessary you can add a similar structure for the messages themselves too.
Finally: this type of recursive loading is not nearly as inefficient as many developers initially think, since Firebase pipelines the requests over an existing connection.

Allow delete and write with Firebase Rules

I am using Firebase Realtime Database. And I have a structure to prevent to many children. I have 2 keys. One for the max(max_people), and one that contains how many children there are (registered_people).
My structure:
I have the max_people key. This is the max children that can be in the approved key. Registered_people is counting how many childs there in the approved key.
This is my security rule:
"registrations": {
"approved": {
".write": "(root.child('/agenda/activitys').child($room_id).child('max_people').val() > root.child('/agenda/activitys').child($room_id).child('registered_people').val())"
}
What I do at my firebase rules, is that I check if there not are to many rows. If there are to many I block the writing. This works as expected.
But now the problem, the max_people is for example 20, and the registered_people is also 20. No writes can happen. Because I have declared that. But how can I allow a delete than. Because I want to delete at every moment.
So in short, I want to delete no matter what. And I want to write with my current rule.
Some more information:
I add data to the key with the following code:
let data = [
"full_name": "test",
"email_addres": "test",
]
Database.database().reference().child("agenda/activitys/" + event + "/registrations/approved").child(Auth.auth().currentUser!.uid).setValue(data) { (error, ref) in
print("got from subscribing \(String(describing: error))")
if((error) != nil){
completionHandler(Result.failure(ApiError.noMorePlaces))
return
} else {
completionHandler(Result.success("succes \(event)"))
return
}
}
Adding works as expected.
And I delete data with the following code:
Database.database().reference().child("agenda/activitys/" + event + "/registrations/approved").child(Auth.auth().currentUser!.uid).removeValue { (error, ref) in
if((error) != nil){
completionHandler(Result.failure(ApiError.unknownError))
return
} else {
completionHandler(Result.success("succes \(event)"))
return
}
}
Deleting does not work as expected. I get a permission_denied error when there are for example a max of 20 keys. And that max is fully used (so I have 20 keys with data under the approved child).
Error:
[Firebase/Database][I-RDB038012] setValue: or removeValue: at /agenda/activitys/Jumping Fitness/registrations/approved/exCnADF43AdFUzGsi0GllEsZJZY2 failed: permission_denied
However deleting works when there a less than the max amount of keys.
Edit:
I have tested the suggested solution on the firebase rules simulator. I got the simulated write error there also.
I think that I have the solution. I delete on the key, so on the rules I need the key also. My solution:
"registrations": {
"approved": {
".write": "(root.child('/agenda/activitys').child($room_id).child('max_people').val() > root.child('/agenda/activitys').child($room_id).child('registered_people').val())",
"$key" : {
".write" : "!newData.exists()"
}
}
When data is being deleted, the newData variable will be null. So you can check if it exists using the exists() method:
"registrations": {
"approved": {
".write": "(root.child('/agenda/activitys').child($room_id).child('max_people').val() > root.child('/agenda/activitys').child($room_id).child('registered_people').val()) || !newData.exists()"
}
Update: After looking at the code you provided, I can see that you do the write operations against the child key. But have in mind that, according to the documentation:
Shallower security rules override rules at deeper paths.
This means that the write rule under "approved" will overwrite the write rule at "$key". So you should join both rules and keep them under the "$key" rule. Like this:
"registrations": {
"approved": {
"$key" : {
".write" : "(root.child('/agenda/activitys').child($room_id).child('max_people').val() > root.child('/agenda/activitys').child($room_id).child('registered_people').val()) || !newData.exists()"
}
}

How can I grant access to array of admins on Firebase database rules

I am stuck trying to allow an an array of admins access to their data.
I have a database structure like this:
{
"Respondents": {
"Acme Corp": {
"admins": ["mMK7eTrRL4UgVDh284HntNRETmx1", ""mx1TERNmMK7eTrRL4UgVDh284Hnt"],
"data": {data goes here...}
},
"Another Inc": {
"admins": ["Dh284HmMK7eTrRL4UgVDh284HntN", ""x1TERNmx1TERNmMK7eTrRL4UgVDh"],
"data": {their data goes here...}
}
}
}
And then I tried to set my rules like this
{
"rules": {
"Respondents": {
"$organisation" : {
".read": "root.child('Respondents').child($organisation).child('admins').val().includes(auth.id)",
".read": "root.child('Respondents').child($organisation).child('admins').val().includes(auth.id)"
}
}
}
}
..but that won't parse in the Firebase Database Rules editor
I get "Error saving rules - Line 7: No such method/property 'includes'", but I need something to match the user id with the array of admins.
Any experience or suggestions?
As you've found, there is no includes() operation in Firebase's security rules. This is because Firebase doesn't actually store the data as an array. If you look in the Firebase Database console or read this blog post you will see that Firebase stores it as a regular object:
"admins": {
"0": "mMK7eTrRL4UgVDh284HntNRETmx1",
"1": "mx1TERNmMK7eTrRL4UgVDh284Hnt"
}
And since that is a regular JavaScript object, there is no contains() method on it.
In general creating arrays are an anti-pattern in the Firebase Database. They're often the wrong data structure and when used are regularly the main cause of scalability problems.
In this case: you're not really looking to store a sequence of UIDs. In fact: the order of the UIDs doesn't matter, and each UID can be meaningfully present in the collection at most once. So instead of an array, you're looking to store set of uids.
To implement a set in Firebase, you use this structure:
"admins": {
"mMK7eTrRL4UgVDh284HntNRETmx1": true,
"mx1TERNmMK7eTrRL4UgVDh284Hnt": true
}
The value doesn't matter much. But since you must have a value to store a key, it is idiomatic to use true.
Now you can test whether a key with the relevant UID exists under admins (instead of checking whether it contains a value):
"root.child('Respondents').child($organisation).child('admins').child(auth.uid).exists()",

How to write to Firebase table only if its greater than current value in table

I need to update the table level value in Firebase score table only if the table value is less than the value currently being posted to update. So the KeyOfLevel value never decreases.
Since the client side involved too much calls to fetch and check. I need to do this in rules tab of Firebase. And I don't exactly know how to write those rules.
Eg:
score:
{
"1234567890":
{
CoinsKey: 1000,
KeyOfLevel: 5
}
}
where 123456789 is the user ID.
You might want to write security rules like this.
{
"rules": {
"score": {
"$userId": {
"KeyOfLevel": {
".validate": "!data.exists() || data.val() < newData.val()"
}
}
}
}
}
In place of .validate you can also use .write

Resources