Firebase chat app setValue failed error with a public database? - android

I have a chat app using Firebase that keeps on having a
setValue at x failed: DatabaseError: permission denied
error every time I type a message.
I set my Database to be public already:
service cloud.firestore {
match /databases/{database}/documents {
match /{allPaths=**} {
allow read, write: if request.auth.uid != null;
}
}
}
Is it something from within my chat reference?
private void displayChat() {
ListView listOfMessage = findViewById(R.id.list_of_message);
Query query = FirebaseDatabase.getInstance().getReference();
FirebaseListOptions<Chat> options = new FirebaseListOptions.Builder<Chat>()
.setLayout(R.layout.list_item)
.setQuery(query, Chat.class)
.build();
adapter = new FirebaseListAdapter<Chat>(options) {
#Override
protected void populateView(View v, Chat model, int position) {
//Get reference to the views of list_item.xml
TextView messageText, messageUser, messageTime;
messageText = v.findViewById(R.id.message_text);
messageUser = v.findViewById(R.id.message_user);
messageTime = v.findViewById(R.id.message_time);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
}
};
listOfMessage.setAdapter(adapter);
}

Your code is using the Firebase Realtime Database, but you're changing the security rules for Cloud Firestore. While both databases are part of Firebase, they are completely different and the server-side security rules for one, don't apply to the other.
When you go the database panel in the Firebase console, you most likely end up in the Cloud Firestore rules:
If you are on the Cloud Firestore rules in the Firebase console, you can change to the Realtime Database rules by clicking Cloud Firestore BETA at the top, and then selecting Realtime Database from the list.
You can also directly go to the security rules for the Realtime Database, by clicking this link.
The security rules for the realtime database that match what you have are:
{
"rules": {
".read": "auth.uid !== null",
".write": "auth.uid !== null"
}
}
This will grant any authenticated user full read and write access to the entire database. Read my answer to this question on more on the security/risk trade-off for such rules: Firebase email saying my realtime database has insecure rules.

change this
request.auth.uid != null
to
request.auth.uid == null
or defined a proper auth mechanism before starting the conversation where user defined by userID

Related

how to check the current Firebase data under uid?

I am trying to check uid from firebase Realtime database, but its only returns the current uid and when I try to check uid with previous uid then also it only returns the current uid. I had tried many ways and searched but I can't get the exact solution, please if any one could help.
here what I am using to check the uid
FirebaseAuth.getInstance().getCurrentUser().getUid();
here is my code how I am trying to check
String userEnteredUserName = binding.textLoginUserName.getEditText().getText().toString().trim();
String userEnteredPassword = binding.textPassword.getEditText().getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
Query checkUser = reference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).orderByChild("userName").equalTo(userEnteredUserName);
Log.d("uids", "uid: " + uid);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
binding.textLoginUserName.setError(null);
binding.textLoginUserName.setErrorEnabled(false);
Log.d("users", "Username: " + snapshot.toString());
if (snapshot.exists()) {
String passwordFromDB = snapshot.child(userEnteredUserName).child("password").getValue(String.class);
if (passwordFromDB.equals(userEnteredPassword)) {
//next activity
}else{
Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();
}
});
In log what I get,
2022-02-06 13:13:06.173 18093-18093/abc C/uids: uid: OFtpR6bfISP3Odd9K1oGWCQmeEf2
Here is my firebase data, "aisha12" is working which is under the current uid but when I try to check "vgbb" it returns only the current uid
If I understand correctly, you are trying to allow a user to register a username and ensuring that the username is unique. Your current data structure doesn't allow you to do that query though.
Firebase Realtime Database can only order/filter on a value that is at a fixed path under each child node of the location you query. So in your current code:
reference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).orderByChild("userName").equalTo(userEnteredUserName);
You are querying the direct child nodes of /Users/$uid looking for the username under there. Since you're specifying the UID in that path, you're only searching under that specific user.
There is no way with your current data structure to search across all /Users, since the property you are looking for is under /Users/$uid/$username/userName, so with two dynamic keys in there, and the database can only handle one dynamic key.
To allow the query, you will need to change the data structure and remove the $userName level from it, so that you get:
Users: {
"3l6Rm....": {
"userName": "vgbb",
...
},
"OftpR...": {
"userName": "aisha12",
...
}
}
Now you can search for the username with:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
Query checkUser = reference.orderByChild("userName").equalTo(userEnteredUserName);
I also recommend checking out these previous questions on allowing a user to register a unique username:
How do you prevent duplicate user properties in Firebase?
Firebase security rules to check unique value of a child #AskFirebase
How to check if usernames are unique in Firebase
unique property in Firebase
How to give unique usernames from a list of usernames to the users in the firebase
Check value already exists or not in Firebase?

How to set firebase read rule and read all siblings if one matches

I have set my firebase rules as follows:
{
"rules": {"users": {
"$uid": {
".read": "auth != null",
".write": "$uid === auth.uid"
}}
}
}
Which allows write only to the node with matching uid and read all child nodes of every uid. But I want it to be like if I query using a child node under uid, only the matching child and it's siblings can be read...
for example this is my json structure:
{
"users" : {
"AJkK4yZJsoseeefrJ7i6KIOUBDghtrhgthrtDi1" : {
"lat" : 20.5001,
"long" : 68.3755,
"number" : "9876543210",
"time" : 1499599788090
}
}
}
I want to query using the number, and set the read rule as can read lat long and time only where the number matches. How to write the rule?
update: my question now is, how to query the database using number and get other siblings if value of number matches in android? I have tried this but not working:}
friend = mDatabase.getReference("users");
friend.keepSynced(true);
Query z = LocationActivity.this.friend.orderByChild("number").equalTo("9876054321");
z.addListenerForSingleValueEvent((new ValueEventListener() {
long lastseen;
public void onDataChange(DataSnapshot dataSnapshot) {
try {
for (DataSnapshot zoneSnapshot: dataSnapshot.getChildren()) {
lastseen = (Long)zoneSnapshot.child("time").getValue();
friendLatitude = (Double) zoneSnapshot.child("lat").getValue();
friendLongitude = (Double) zoneSnapshot.child("long").getValue();
}
} catch (Exception e) {
}}
it returns value null, any help would be appreciated.
Firebase read permissions are enforced when you attach a listener. In order to query a node, you must have read permission on that node (as Bradley also explained). So in order to be able to query users, you must have read permission on /users. And since any user that has read permission to /users can also read any data under that, you cannot use security rules to filter what nodes a user has access to.
This is known as rules are not filters and is one of the common pitfalls for developers new to Firebase security model. I recommend that you read the documentation I linked already and some of the many questions/answer about the topic.
The simplest solution for your use-case seem to be to pull up the .read rule to users:
{
"rules": {
"users": {
".read": "auth != null",
"$uid": {
".write": "$uid === auth.uid"
}
}
}
}
}
In order to query every node, the user needs to have read permission for ALL nodes under the parent.
This is because security rules cannot be used to query data in Firebase.
Not exactly sure if this answers the question, but I found this post looking for the following solution with respect to Firebase Storage .. where I can control which sibling nodes are accessible:
match /uploadRoot/{userId}/{uploadCategory}/{allPaths=**} {
// allow read access for client upload/download
allow read, write:
if request.auth != null
&& request.auth.uid == userId
&& (
uploadCategory == 'userTextFiles'
|| uploadCategory == 'userImages'
);

Rule entries duplicates firebase not working

I have an application in android that registers sellers, which have a unique email, I am storing them in firebase. Create a rule to not allow duplicates to be added but it does not seem to work. What am I doing wrong?
{
"rules": {
".read": true,
".write": true,
"sellers": {
"$seller": {
"email": {
".write": "!data.exists()"
}
}
}
}
}
my method to add
public void addSeller(Seller seller){
HashMap<String,Seller> map= new HashMap<>() ;
String email = seller.getEmail().replace(".",",");
map.put(email,seler);
database.child("sellers").setValue(map);
}
You're calling push(), which generates a new child that is statistically guaranteed to be unique.
If you want to ensure unique email addresses, you will have to keep a collection where the (encoded) email addresses are the keys:
emails
pete#somedomain,com
puf#somedomain,com
With this structure, the following rule will work to ensure an email address can only be written once:
{
"rules": {
".read": true,
"emails": {
"$email": {
".write": "!data.exists()"
}
}
}
}
The topic of unique values comes up regularly, so I recommend you also check out these:
Firebase android : make username unique
How do you prevent duplicate user properties in Firebase?
Enforcing unique usernames with Firebase simplelogin
unique property in Firebase
Firebase Unique Value
What Firebase rule will prevent duplicates in a collection based on other fields?

How to implement ondelete cascade in Firebase (Android)

I am new with Firebase. I want to implement ondelete cascade in Firebase.
Here is the problem for which I want solution
I have two table "users" and "groups".
{ "users":{
"user1":{
"username":"john",
"full_name":"John Vincent",
"created_at":"9th Feb 2015",
"groups":{
"group1":true,
"group3":true
}
"last_logins":...
},
"user2": ...,
"user3": ...
}"groups": {
"group1"{
"group_name":"Administrators",
"group_description":"Users who can do anything!",
"no_of_users":2,
"members":{
"user1":true,
"user3":true
}
},
"group2"{
"group_name":"Moderators",
"group_description":"Users who can only moderate!",
"no_of_users":1,
"members":{
"user2":true
}
}
}
}
Please pardon me for above code indentation.
Now if I removed user1 from users table then how it should be automatically removed from groups table using Firebase.
This can easily done using SQL but I don't know how to do this in Firebase. One way to do this in Firebase is to remove user1 from users and then makes group1 and group3 to null and then in groups table make user1 to null under group1/member but this need 2-3 calls. So is there any another best way to do this.
Please help me I am stuck here.
The Firebase Database has no knowledge of relations between values in its JSON tree. In SQL/relations terms: it doesn't have the concept of foreign keys. This means that it also doesn't have an option to delete related objects with a cascading delete. You will need to delete each value separately.
But you can combine all those deletes into a single call by using multi-location updates. If you write null to each of the locations for the user, you can delete all of them with one call to updateChildren():
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map<String,Object updates = new HashMap<String,Object>();
updates.put("users/user1", null);
updates.put("groups/group1/members/user", null);
// Do a deep-path update
ref.updateChildren(updatedUserData, new Firebase.CompletionListener() {
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
if (firebaseError != null) {
System.out.println("Error updating data: " + firebaseError.getMessage());
}
}
})
With this in place, you could then write security rules that validate that members of a group must also exist under the /users node:
{
"rules": {
"groups":
"$groupid": {
"users": {
"$uid": {
".validate": "newData.parent().parent().parent().parent().child('users').hasChild($uid)"
}
}
}
}
}
}
The validation rule is a bit easier to understand if you read the multiple .parent() calls as newRoot (which unfortunately doesn't exist). So in pseudo-code it is:
newRoot.child('users').hasChild($uid)
In words: a UID can only be a member of a group if it also exists under /users.

Does firebase realtime data create a new instance for each user or does everything just get stored in a large tree

I am new to firebase and Nosql databases. I have gone through the documentations already, but I cannot seem to get my head around a concept.
I have gone through almost every question on here about it, but everyone just seem to conveniently skip the little detail i am looking for.
Suppose I have successfully registered my users using firebaseauth, and can log them in and out, I have my database rules as follows
{
"rules": {
"users":{
"$userid":{
".read": "auth !== null && auth.uid == $userid",
".write": "auth !== null && auth.uid == $userid"
}
}
}
}
Great!, now thats the basic database for a multiuser application. My question is that the users data doesnt get pushed to database from auth automatically, so i have to do a
mRef = FirebaseDatabase.getInstance().getReference();
mUserRef = mRef.child("users");
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uid = mAuth.getCurrentUser().getUid();
String name = "User " + uid.substring(0, 6);
Userid userid = new Userid(uid);
mUserRef.push().setValue(userid, newDatabaseReference.CompletionListener() {
and so on, on the registeractivity so any userid can have its own node under users where i can post any user specific data.
I have not implemented this yet, but i forsee that for any read or write data performed by a user will have to search every node to find its own userid, which would take a lot of time when you scale up to like a lot of users and im sure firebase is better than that. So is this how firebase expect us to handle user stuff or does every user just have his own database instance
The push() method creates a new, random ID. This is useful for things like messages in a chat application, but is likely not what you are looking for.
I think you mean to do this:
// Get current UID
String uid = mAuth.getCurrentUser().getUid();
// Get reference to /users/<uid>
DatabaseReference ref = mUserRef.child(uid);
// Set the value of /users/<uid> to the UserId
Userid userid = new Userid(uid);
ref.setValue(userid);

Categories

Resources