I have in the security & rules option this:
{
"rules": {
".read": true,
".write": true,
"groups": {
".indexOn": "name"
}
}
}
And my JSON structure is like this:
{
"groups": {
"-KAti17inT7GbHEgbzzS": {
"author": "ruben",
"name": "C"
},
"-KAti36BQGO8sRmfufkE": {
"author": "ruben",
"name": "D"
},
"-KAti2CVAHtJllQm_m-W": {
"author": "ruben",
"name": "A"
}
}
As you can see, it is not ordered by "name", as is it supposed to be.
What I'm doing wrong?
That .indexOn instruction in the security rules only tells the database to create an index on the name property. It doesn't automatically re-order the data.
In addition: the order of keys in a JSON object is undefined.
To get a list of your groups by name, you have to execute a Firebase query. From the Firebase documentation on queries:
let ref = Firebase(url:"https://dinosaur-facts.firebaseio.com/dinosaurs")
ref.queryOrderedByChild("height").observeEventType(.ChildAdded, withBlock: { snapshot in
if let height = snapshot.value["height"] as? Double {
println("\(snapshot.key) was \(height) meters tall")
}
})
If you adapt this snippet to your data structure, it will print the groups in the correct order.
Related
I want to write a rule in Firebase to allow only the user to be able to write to the database when the disable is set to false.
The structure of my database is as follows:
{
"Users": {
"UID": {
"details": {
"random key generated by push": {
"disable": true,
},
}
To read a value from another node inside your security rules, you have to know the exact path to that node. So unless you know the value of "random key generated by push", there is no way to read that from the rules on one of the nodes above it.
This usually means that you should change your data structure to have the disable flag at a known location under the UID node. For example:
{
"Users": {
"UID": {
"disable": true,
"details": {
"random key generated by push": {
},
}
Now you can allow access to UID node like this:
{
"rules": {
"Users": {
"$uid": {
".read": "data.child('disable').val() === true"
}
}
}
}
I have a realtime db all setup and working. The data structure is very simple:
Item
some: info
some: other info
Item 2
some: info
some: other info
My rules are also super simple:
{
"rules": {
".read":"auth.uid != null",
".write":"auth.uid != null"
}
}
The issue (obviously) is that while I am forcing a user to be authenticated, that's all I am requiring and any user can access all the items in the db.
What I want is a way to limit a user to an item.
something like:
Item1
some: info
some: other info
user_1: auth.uid
user_2: auth.uid2
Item2
some: info
some: other info
user_1: auth.uid3
user_2: auth.uid4
I can store that data but I am not sure how to structure my rules to limit that.
My actual json looks like:
{
"annotations": {
"8df0309f-dc62-821e-dd65-f0ad46396937": {
"author": "1OXVKN3Y5Z-11",
"xfdf": "LONG STRING"
}
},
"complete": false,
"created_at": "2020-09-01T17:52:25.653Z",
"field_values": {
"field_name": {
"name": "copy",
"value": "TEsting",
"widgetID": "e61e3abf-7cdd-7d07-daec-6c3d3a55d667"
}
},
"stamp_count": 0
}
What I plan to implement is:
{
"annotations": {
"8df0309f-dc62-821e-dd65-f0ad46396937": {
"author": "1OXVKN3Y5Z-11",
"xfdf": "LONG STRING"
}
},
"complete": false,
"created_at": "2020-09-01T17:52:25.653Z",
"field_values": {
"field_name": {
"name": "copy",
"value": "TEsting",
"widgetID": "e61e3abf-7cdd-7d07-daec-6c3d3a55d667"
}
},
"stamp_count": 0,
"users": [ "CFX4I0PTM9-11", "CFX4I0PTM9-7"]
}
One I implement that json structure, how can I setup rules to support?
From reading your question and the comment thread I think your requirement is:
Allow a user to access an item if their UID is associated with that item.
In that case, you'll first need to ensure that the UIDs are in keys, as you can't search across multiple values, as your proposed users array would require. So you'd end up with:
"items": {
"item1": {
...
"users": {
"CFX4I0PTM9-11": true,
"CFX4I0PTM9-7": true
}
}
}
Now with this structure, you can ensure a user can only update items where their UID is in the users map with rules like this:
{
"rules": {
"items": {
"$itemid": {
".write": "data.child('users').child(auth.uid).exists()"
}
}
}
}
For reading the specific item you could use a similar rule. That will allow the user to read an item once they know its complete path, and when their UID is in the users map.
But you won't be able to query this structure, as you can only index on named properties. For more on this, and the alternative data structure to still implement you use-case, see Firebase query if child of child contains a value
Firebase Data Structure
{
"books": {
"-KaKjMMw-WQltqxrGEmj": {
"categories": {
"cat1": true,
"cat2": true
},
"author": "user1",
"title": "event1"
},
"-KaKjMMw-WQltqxrGEmk": {
"categories": {
"cat1": true,
"cat2": false
},
"author": "user1",
"title": "event2"
}
}
}
Query To find all books of a particular author
FNode.testNode.child("books")
.queryOrderedByChild("author")
.queryEqualToValue("user1")
.observeEventType(.Value) { (snapshot) in
print(snapshot)
}
Question:
I want to find all the books belonging to cat1. Couldn't figure out the query to do that.
After a lot of hit and trial, finally got my answer.
For the above structure. If you want to find all the books belonging to cat1 Here is the query for that:
FNode.testNode.child("books")
.queryOrderedByChild("categories/cat1").queryEqualToValue(true)
.observeEventType(.Value) { (snapshot) in
print(snapshot)
}
Note: FNode.testNode could be any node of type FIRDatabaseReference
To Firebase Team: Can you please include a sample of all possible firebase queries in data structures and put it alongside firebase docs. It's kind of hit-and-trial for us now.
I have data saved to a Firebase Database with complex relationships indexed as outlined here similar to the example below.
{
"groups": {
"alpha": {
"name": "Alpha Group",
"members": {
"mchen": true,
"hmadi": true
}
},
...
},
"users": {
"mchen": {
"name": "Mary Chen",
// index Mary's groups in her profile
"groups": {
// the value here doesn't matter, just that the key exists
"alpha": true
},
},
...
},
"animals": {
"dog": {
"users": {
// the value here doesn't matter, just that the key exists
"mchen": true
},
},
...
},
}
For my project, what I need to do is I need to get a list of group members for all users who like dogs. This means means getting one reference, then another, then another. If I want to get the group members of people who like dogs, I'd Fetch
animals>dog>mchen
user>mchen>groups>alpha
groups>alpha ... members(final result)
Given that this is all done asynchronously, how would I conduct these data retrievals with conditions of completion, chaining one to the next? I've already tried nesting completion handlers, and this doesn't seem to work.
Each user has a conversation node, each time a new conversation has a new message I need to update both conversation nodes for the two user involved in the conversation, I want just to update the "lastMessage" and "tinestamp" fields here is my try:
let fanoutObject = [userPath : dataToUpdate,
otherUserPath : dataToUpdate]
K.FirebaseRef.root.updateChildValues(fanoutObject)
where the paths for each user is:
"/users/{userID}/conversations/{conversationID}"
and the dataToUpdate:
let dataToUpdate:[String:AnyObject] = ["timestamp" : message.timestamp,
"lastMessage": message.textBody]
Result:
The node conversations for each user is updated BUT other fields in the conversation node are removed !
the conversation node fro each user is:
"conversations" : {
"{conversationID}" : {
"lastMessage" : "your name ?",
"seen" : true,
"timestamp" : 1467849600000,
"with" : {
"country" : "US",
"firstName" : "John",
"profileImage" : "https://..."
}
}
}
note that the node conversations is inside a node user which is an element inside the root node users
and after update it's :
"conversations" : {
"{conversationID}" : {
"lastMessage" : "your name ?",
"timestamp" : 1467849600000,
}
}
but I was expecting just to update the two values and keep others ?
According to docs my code should works:
updateChildValues Update some of the keys for a defined path without
replacing all of the data.
It's a bit hard to parse your code, but most likely it's the behavior of updateChildValues() that is confusing you.
When you call updateChildValues(), the Firebase server will loop over the object that you pass in. For each path in there, it will replace the entire value at that path with the value from that you passed in.
So if your current JSON is:
{
"Users": {
"uidForUser1": {
"name": "iOSGeek",
"id": 2305342
},
"uidForUser2": {
"name": "Frank van Puffelen",
"id": 209103
}
}
And the update is (in JSON format, the lingua franca of the Firebase Database):
{
"users/uidForUser2/name": "puf",
"users/uidForUser1/name": "My actual name"
}
Your resultant JSON will be:
{
"Users": {
"uidForUser1": {
"name": "My actual name",
"id": 2305342
},
"uidForUser2": {
"name": "puf",
"id": 209103
}
}
But if you send the following update:
{
"users/uidForUser1": {
"name": "My actual name"
},
"users/uidForUser2": {
"name": "puf"
}
}
The resulting JSON will be:
{
"Users": {
"uidForUser1": {
"name": "My actual name"
},
"uidForUser2": {
"name": "puf"
}
}
Update
To update two fields in the same object, but leave the other fields unmodified:
{
"path/to/object/field1": "new value",
"path/to/object/field2": "new value2"
}
Alternatively, you can update the lastMessage and timeStamp data by replacing the old values by providing full path :
let lastMessagePath = "/users/{userID}/conversations/{conversationID}/lastMessage"
let lastTimeStampPath = "/users/{userID}/conversations/{conversationID}/timestamp"
K.FirebaseRef.child(lastMessagePath).setValue(message.timestamp)
K.FirebaseRef.child(lastTimeStampPath).setValue(message.textBody)