In my project I have a chat feature to allow users to speak in private message. For now it's only one-to-one, but it could be improved later to allow group discussion.
Currently I'm struggling with custom rules. Indeed, for my projet I need users to have theirs own list of discussion. For example, user A and B talk through private message, but user C, D or whatever shouldn't be able to read the discussion.
Here is how the Database json look like :
{
"room-messages": {
"-KWgoXt567vzgxZ-1gii": {
"-KWgoXt567vzgxZ-1gii": {
"name": "Friendly Chat",
"sent": 1479294463723,
"text": "Nice ! You have created a new chat",
"uid": "user_A_id"
},
"-KWh5_W12qsXFaJhyOvx": {
"name": "Lucien Guimaraes",
"sent": 1479294463728,
"text": "A text message",
"uid": "user_B_id"
}
},
"-KWgoXt567vzgxZ-1git": {
"-KWgoXt567vzgxZ-1git": {
"name": "Friendly Chat",
"sent": 1479294463723,
"text": "Nice ! You have created a new chat (2)",
"uid": "user_A_id"
},
"-KWh5_W12qsXFaJhyOvz": {
"name": "Lucien Guimaraes",
"sent": 1479294463729,
"text": "Test",
"uid": "user_C_id"
}
}
},
"room-metadata": {
"-KWgoXt567vzgxZ-1gii": {
"users": {
"user_A_id": "Lucien Guimaraes",
"user_B_id": "Geralt of Rivia"
}
},
"-KWgoXt567vzgxZ-1git": {
"users": {
"user_A_id": "Lucien Guimaraes",
"user_C_id": " Gordon Freeman"
}
}
}
}
For your information "user_A_id" or "user_B_id" should be the id provided by Firebase Authentication. In this example I want user A to get all rooms (because he's in both available room). User B should have only the first room and user B only the last room.
Here are my rules :
I have been able to allow write access for Rooms almost perfectly (the only remaining issue is user who can't delete a message, I don't know why). But for Read I have a huge issue : I can't set a custom rule because the value "$roomId" is unknown inside "room-messages". It's only possible to do this as a child of "$roomId".
Is there any solution for what I want implemented ?
Thanks !
#AskFirebase
Related
Problem
We've been using OPA to do data authorization of our REST HTTP APIs. We secure our APIs as such
allow {
input.method == "GET"
glob.match(input.path, ["/"], "/department/DEPARTMENT_ID/employee/")
some_rule # Where we check that user can list all employee in the particular deparment/DEPARTMENT_ID based on the ACL of department/DEPARTMENT_ID
}
As seen above, each department has its own ACL we authorize against that for any access to it and its child resources (e.g. employee).
We query this policy via OPA's HTTP API, and we push department/DEPARTMENT_ID's ACL to OPA for it to make a decision. See OPA docs.
However, there's been a new requirement where we have to make an API that has to list all employee that the user has access to.
How could one go about doing this given that the authorization can no longer look at just one ACL? (because multiple employee resources will belong in different department, each with their own ACL).
Potential solution
When listing employee, we could send OPA all the ACLs of each of their department (i.e. the parent), and have OPA authorize based on that. This could be highly inefficient, but I'm not sure if there's any better way. The size of this is also bounded if we paginate the employee listing.
I'm not sure I followed entirely, but given that you have data looking something like the below:
{
"departments": {
"department1": {
"permissions": {
"jane": ["read"]
},
"employees": {
"x": {},
"y": {},
"z": {}
}
},
"department2": {
"permissions": {
"jane": ["read"]
},
"employees": {
"a": {},
"b": {},
"c": {}
}
},
"department3": {
"permissions": {
"eve": ["read"]
},
"employees": {
"bill": {},
"bob": {},
"eve": {}
}
}
}
}
And input looking something like this:
{
"user_id": "jane",
"method": "GET",
"department_id": "department1",
"path": "/department/department1/employee"
}
A policy to query for all listable employees for a user might look something like this:
package play
import future.keywords.in
allow {
input.method == "GET"
glob.match(input.path, ["/"], sprintf("/department/%v/employee", [input.department_id]))
can_read
}
# Where we check that user can list all employee in the particular deparment/DEPARTMENT_ID based on the ACL of department/DEPARTMENT_ID
can_read {
"read" in data.departments[input.department_id].permissions[input.user_id]
}
listable_employees[employee] {
some department in data.departments
"read" in department.permissions[input.user_id]
some employee, _ in department.employees
}
The listable_employees in this case would evaluate to:
[
"a",
"b",
"c",
"x",
"y",
"z"
]
Since user jane has read access to department1 and department2, but not department3.
I am checking a if a email is already registered or not
query=googleRef.orderByChild("email").equalTo(newEmail).addValueEventListener(object :ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
println(p0.code)
}
override fun onDataChange(p0: DataSnapshot) {
if(p0.exists())
{
println("Yes user exists")
}
else if(!p0.exists())
{
println("Users dont exists")
}
}
Code from comments:
I had used a push for inserting:
googleRef.child("userID").push().setValue(userId)
googleRef.child("gname").push().setValue(userName)
googleRef.child("email").push().setValue(reEmail)
googleRef.child("photoUrl").push().setValue(userpicUrl)
If you add two users, the way you're adding code is going to result in a structure like this:
"googleRef": {
"userID": {
"-Ldfs32189eqdqA1": "userID1",
"-Ldfs32189eqdqA5": "userID2"
},
"gname": {
"-Ldfs32189eqdqA2": "gname1",
"-Ldfs32189eqdqA6": "gname2"
},
"email": {
"-Ldfs32189eqdqA3": "email1",
"-Ldfs32189eqdqA7": "email2"
},
"photoUrl": {
"-Ldfs32189eqdqA4": "photoUrl1",
"-Ldfs32189eqdqA8": "photoUrl2"
}
}
So you have a separate generated push ID (the keys starting with a -) for each property of each user, which is highly uncommon.
The more idiomatic form of storing user information is either this:
"googleRef": {
"-Ldfs32189eqdqA1": {
"userID": "userID1",
"gname": "gname1",
"email": "email1",
"photoUrl": "photoUrl1"
},
"-Ldfs32189eqdqA5": {
"userID": "userID2",
"gname": "gname2"
"email": "email2"
"photoUrl": "photoUrl2"
},
}
Or (even better) this:
"googleRef": {
"userID1": {
"gname": "gname1",
"email": "email1",
"photoUrl": "photoUrl1"
},
"userID2": {
"gname": "gname2"
"email": "email2"
"photoUrl": "photoUrl2"
},
}
The reasons these last two are more common is that they group the information for each user together, which makes it easier/possible to find information for each user. In both of these cases, you can find users with a specific email address with your query.
The reason the last one is best, is because the information for each user is stored under the user's ID, which is already guaranteed to be unique. This structure makes looking up the user's information by their UID possible without needing a query.
To write a structure like the last example, use:
Map<String, Object> values = new HashMap<>();
values.put("gname", userName)
values.put("email", reEmail)
values.put("photoUrl", userpicUrl)
googleRef.child(userId).setValue(values)
A final note: you can't return whether the node exists or node, since the data is loaded from Firebase asynchronously. To learn more about what that means, and the common workaround (which is to define a callback interface), see getContactsFromFirebase() method return an empty list
Can I query multiple keywords in firestore? How I can match an array of keywords in firestore?
I have a collection of documents with a title, I want to query articles contains specific keywords.
Following is my document structure.
{
"users": {
"user_id_1": {
"username": "user one",
"profile_pic": "some_url",
"articles": {
"article_id_1": {
"title": "Firebase is so cool",
"comments": {
"comment_id_1": "First comment",
"comment_id_2": "I like trains"
}
},
"article_id_2": {
"title": "Firestore rocks!",
"comments": {
"comment_id_1": "SQL it's better",
"comment_id_2": "Do you know the wae?"
}
},
"article_id_3": {
"title": "Firestore awesome",
"comments": {
"comment_id_1": "SQL it's better",
"comment_id_2": "Do you know the wae?"
}
},
"article_id_4": {
"title": "Firestore is easy",
"comments": {
"comment_id_1": "SQL it's better",
"comment_id_2": "Do you know the wae?"
}
}
}
}
}
}
Here I want to search articles based on the following keywords.
["cool", "rocks", "Firestore is easy"]
I should get article_id_1, article_id_2 and article_id_4
Thanks.
This is not possible with Firestore alone. It's not a text search engine. You will want to export your data to a text search engine such as Algolia in order to perform text searches that are not based on simple text equality. The documentation suggests this solution.
Let's take a look at "Instagram-like" app, as an example.
In the feed we got posts, with user avatar and name at the top, photo or video below, and last comments, likes count and post time at the bottom.
Basically, at the client I'm waiting to get from backend something like
{
username: "John",
avatar:"some_link",
photo:"photo_url",
likes:"9",
time:"182937428",
comments:[comments there]
}
but using Firebase, I need to store data in more flat way. so there will be "users", "posts" and "comments" in data JSON.
How am I suppose to aggregate data from those nodes in some kind of single object, which is easy to use at client?
Or should I ask Firebase for posts, than for all users in it, and for all their comments, and do aggregation after all three 'requests' are done?
You should implement "shallow" tree structure, and use references where needed.
That means that for most cases in your app you should use the object as at is, Making sure that it contain the "essential data" (in the example below "the chat title"), and keys for "further" information (in the example, keys to the "members").
from firebase docs (https://firebase.google.com/docs/database/web/structure-data):
bad
{
// This is a poorly nested data architecture, because iterating the children
// of the "chats" node to get a list of conversation titles requires
// potentially downloading hundreds of megabytes of messages
"chats": {
"one": {
"title": "Historical Tech Pioneers",
"messages": {
"m1": { "sender": "ghopper", "message": "Relay malfunction found. Cause: moth." },
"m2": { ... },
// a very long list of messages
}
},
"two": { ... }
}
}
good
{
// Chats contains only meta info about each conversation
// stored under the chats's unique ID
"chats": {
"one": {
"title": "Historical Tech Pioneers",
"lastMessage": "ghopper: Relay malfunction found. Cause: moth.",
"timestamp": 1459361875666
},
"two": { ... },
"three": { ... }
},
// Conversation members are easily accessible
// and stored by chat conversation ID
"members": {
// we'll talk about indices like this below
"one": {
"ghopper": true,
"alovelace": true,
"eclarke": true
},
"two": { ... },
"three": { ... }
},
// Messages are separate from data we may want to iterate quickly
// but still easily paginated and queried, and organized by chat
// conversation ID
"messages": {
"one": {
"m1": {
"name": "eclarke",
"message": "The relay seems to be malfunctioning.",
"timestamp": 1459361875337
},
"m2": { ... },
"m3": { ... }
},
"two": { ... },
"three": { ... }
}
}
I am newbie to Firebase and working on to create events using firebase. Here i am inviting my friends using their phone number.(It is not necessary that whom i am inviting will be part of the system user.)
Below is my schema:
{
"events": [
{
"message": "Lunch",
"startTime": 1469471400000,
"eventCreatorId": 1,
"endTime": 1469471400000,
"invitees": [
{
"phone": "1234567890",
"type": "phone"
},
{
"phone": "345678901",
"type": "phone"
}
]
}
]
}
Now problem is that how i can find list of all events for specific invites?? (i.e in above case i want to find list of all events for user with phone number eqaul to 345678901.)
Can anyone suggest good schema to handle above scenario with firebase?
Welcome to using a NoSQL database. :-)
In NoSQL you often end up modeling the data different, to allow the queries that you want your app to execute. In this case, you apparently want to both show the invitees per event and the events per invitee. If that is the case, you'll store the data in both formats:
{
"events": {
"event1": {
"message": "Lunch",
"startTime": 1469471400000,
"eventCreatorId": 1,
"endTime": 1469471400000,
"invitees": {
"phone_1234567890": true,
"phone_345678901": true
}
}
},
"users": {
"phone_1234567890": {
"phone": "1234567890",
"type": "phone",
"events": {
"event1": true
}
},
"phone_345678901": {
"phone": "345678901",
"type": "phone"
"events": {
"event1": true
}
}
}
}
You'll see that I've split your data into two separate top-level nodes: events and users. They refer to each other with so-called explicit indexes, essentially a set of foreign keys that you manage (and join) in your client-side code.
I've also replaced you arrays with named keys. If your events/users have natural keys (such as uid for identifying the user if you happen to use Firebase Authentication) you'd use that for the key. But otherwise, you can use Firebase push ids. Using such keys leads to a more scalable data structure then depending on array indices.
Both of these topics are covered in the Firebase documentation on data structuring. I also highly recommend this article on NoSQL data modeling.