I just start working with firebase and im working on a project that user can Mark clinic appointments so i add some rules on firabase. Only the owner can read and write his own appointments.
I can write to firabase with no problem, but i cant read from it.
this is my code:
this is how i fetch th data
Firebase ref = new Firebase(Config.FIREBASE_URL).child("Consultas");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Consultas consulta2 = postSnapshot.getValue(Consultas.class);
String consulta1 = "Consulta de: "+consulta2.getNomeconsulta()+"\n";
String medico1 = "Com o Médico: "+consulta2.getNomemedico()+"\n";
String data1 = "Marcada para: "+consulta2.getHorario()+"\n\n";
String time = "Marcada para: "+consulta2.getTime()+"\n\n";
textView1.setText(consulta1);
textView2.setText(medico1);
textView3.setText(data1);
textView4.setText(time);
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
This are my rules on firebase
{
"rules": {
// User profiles are only readable/writable by the user who owns it
"users": {
"$UID": {
".read": "auth.uid == $UID",
".write": "auth.uid == $UID"
}
},
// Posts can be read by the user who owns it/ written by the user who owns it.
"Consultas": {
"$UID": {
".read": "auth.uid == $UID",
".write": "auth.uid == $UID"
}
}
}
}
Thanks
FirebaseRules user === to equal values, you should change your code to:
{
"rules": {
// User profiles are only readable/writable by the user who owns it
"users": {
"$UID": {
".read": "auth.uid === $UID",
".write": "auth.uid === $UID",
}
},
// Posts can be read by the user who owns it/ written by the user who owns it.
"Consultas": {
"$UID": {
".read": "auth.uid === $UID",
".write": "auth.uid === $UID",
}
}
}
}
You can read more about it in the official documentation
Related
I made a chat application using firebase realtime database. Users can send private messages to each other. How should the rules part be? I keep getting emails from Firebase that the rules are not reliable.
This is my firebase Collections:
This is my firebase Rules:
{
"rules": {
".read": "auth.uid!=null",
".write": "auth.uid!=null",
}
}
Only an authenticated admin user can read and write their own admin-user data:
{
"rules": {
"admin-users": {
"$userId": {
".read" : "auth.uid === $userId",
".write": "auth.uid === $userId"
}
}
}
}
Or:
{
"rules": {
"admin-users": {
"$user": {
".read" : "data.child('userUid').val() === auth.uid",
".write": "data.child('userUid').val() === auth.uid"
}
}
}
}
An authenticated user can read all data under Users.
An authenticated user can can only update their own data except the 'userUid' field. Can only update the 'userUid' field if it is a new document creation ('!data.exists()') e.g when it is a signup/register.
An authenticated admin can read and write all the data in Users including the 'userUid' field.
{
"rules": {
"users": {
".read": "auth !== null",
"$userId": {
"userId": {
".write": "root.child('admin-users').child(auth.uid).exists() || !data.exists()"
},
"$other_fields": {
".write": "$userId === auth.uid || root.child('admin-users').child(auth.uid).exists()"
}
}
}
}}
Only Admins can read and write everything in under Chats
Authenticated users can read chat messages in which their userUid matches either 'senderId' or 'receiverId'
Authenticated users can write/update a message only if their userUid matches 'senderId'.
{
"rules": {
"chats": {
".read": "root.child('admin-users').hasChild(auth.uid)",
".write": "root.child('admin-users').hasChild(auth.uid)",
"$chat": {
"$message": {
".read": "auth !== null && data.child('receiverId').val() === auth.uid || data.child('senderId').val() === auth.uid",
".write": "auth !== null && !data.exists() || data.child('senderId').val() === auth.uid"
}
}
}
}}
These sample rules are just to give guidance on how security rules work. You can create different rules that can work as well with your use case. See link for more details https://firebase.google.com/docs/rules/insecure-rules
https://firebase.google.com/docs/database/security/core-syntax
I am developing a rudimentary delivery app using android studio and I am using Firebase as the database. I need to save the user info and also products that all the users can select from.
So basically each user has access to only their details but each user can access details from all the Products.
Here are my rules for the database:
{
"rules": {
"users": {
"$uid": {
".read": "auth != null",
".write": "auth != null"
}
},"Products": {
"$uid": {
".read": true,
".write": true
}
}
}
}
And the database structure:
pat-2017-42536
Products
1
Description: "Product description"
Name: "Name of product"
Price: "Price of product"
2
Description: "Product description"
Name: "Name of product"
Price: "Price of product"
etc...
I tried changing the permissions to true as some previous questions suggested but it still keeps giving me this error:
W/SyncTree: Listen at /Products failed: DatabaseError: Permission denied
This is in my onCreate in Andoid Studio:
databaseProducts = FirebaseDatabase.getInstance().getReference("Products");
databaseProducts.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is the method that is supposed to fetch the product details:
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot productSnapShot: dataSnapshot.getChildren()){
Product product = productSnapShot.getValue(Product.class);
product.setName(productSnapShot.child("item").getValue(Product.class).getName());
product.setDescription(productSnapShot.child("item").getValue(Product.class).getDescription());
product.setPrice(productSnapShot.child("item").getValue(Product.class).getPrice());
ArrayList<String> array = new ArrayList<>();
array.add(product.getName());
array.add(product.getDescription());
array.add("R" + product.getPrice() + ".00");
Log.d(TAG,"showData: name " + product.getName());
Log.d(TAG,"showData: description " + product.getDescription());
Log.d(TAG,"showData: price " + product.getPrice());
ArrayAdapter adapter = new ArrayAdapter(CustomerActivity.this,android.R.layout.simple_expandable_list_item_1,array);
listViewProducts.setAdapter(adapter);
}
}
It is probably a simple error but I can't seem to find it. Any help?
The problem is that you try to read at /Products while you allow read at /Products/Something. Enable read at Products node.
Your rules should be something like
{
"rules": {
"users": {
"$uid": {
".read": "auth != null",
".write": "auth != null"
}
},
"Products": {
".read": true,
".write": true
}
}
}
I don't think the above answer Birendra provided will do what you want it to. I believe that that will allow any authenticated user to read and write in any other specific users id. This is the same as the default rules, but just specific to the users id. He is right about the fact that you have it set up so that it is looking for /Products/$uid and so if you want anyone at all (whether authenticated or not) to both read and write to your products list then that would be the rules--but I can't imagine that you want your products list to be modifiable by everyone. From what I understand you want users to be able to read and write their own account info, but everybody can access the products. I'm not sure if you only want authenticated users to be able to view the products or not, so I'll include the rules for both. Remember, your read and write rules do NOT have to be the same for a particular node. So if you wanted to have every authenticated user be able to see the information of other users but only that particular user can write to their own profile, and if you want your "products" to be viewable by the general public (authentication not required), but you obviously don't want the public messing with your products you could have rules like this:
{
"rules": {
"users": {
".read": "auth != null", //all authenticated users can read the information from the "users" node.
"$uid": {
".write": "$uid === auth.uid" //only a user with an authenticated uid that matches the uid of the child node will be able to write to their node--no need for a read rules because it is already covered in the parent node
}
},
"Products": {
".read": true,
".write": false //you don't want just anybody to write to this node--probably even better since this wouldn't allow anyone to modify the products is to set it up with an admin access where a specific uid is the only one that has access--such as ".write": "auth.uid === 'dJrGShfgfd2'"
}
}
}
If you want only authenticated users to be able read the products, but not modify the products, then you would want:
{
"rules": {
"users": {
".read": "auth != null",
"$uid": {
".write": "$uid === auth.uid"
}
},
"Products": {
".read": "auth != null",
".write": false
}
}
}
Finally, if authenticated users can add or modify products, then you would want:
{
"rules": {
"users": {
".read": "auth != null",
"$uid": {
".write": "$uid === auth.uid"
}
},
"Products": {
".read": "auth != null",
".write": "auth != null"
}
}
}
Make the rules to be as shown below
Make sure that you have chosen REALTIMEDATABASE.
{
security rules. */
"rules": {
".read": true,
".write": true
}
}
There will be two DATA bases
1) cloud firestore
2) Real Time data Base
Choose the real time database and change the rules as the above mentioned one.
The above rule makes it visible to all the people.
in my Android app I want to implement real-time database by Firebase.
The rules are not very simply:
--AUTHOR: write periodicals strings
----ADMIN: create a "chat/room" and invite friends
------MEMBER: read periodicals strings and write own data.
Also:
ADMIN is also a MEMBER.
Every "chat/room" is about 10 MEMBERS.
MEMBER can write its own data and read periodical strings (by author) and the data of the
other 9 members.
Actually, my rules' code is:
{
"rules": {
"chats": {
"$chatID": {
"messages": {
".read": "data.parent().child('members').child(auth.uid).exists()",
".write": "data.parent().child('members').child(auth.uid).val() == 'owner' || data.parent().child('members').child(auth.uid).val()=='chatter'"
},
"members": {
".read": "data.child(auth.uid).val() == 'owner'",
".write": "data.child(auth.uid).val() == 'owner' ||(!data.exists()&&newData.child(auth.uid).val()=='owner')"
},
"pending": {
".read": "data.parent().child('members').child(auth.uid).val() === 'owner'",
".write": "data.parent().child('members').child(auth.uid).val() === 'owner'",
"$uid": {
".write": "$uid === auth.uid && !data.exists() && !data.parent().parent().child('members').child($uid).exists()"
}
}
}
}
}
}
I'm not able to work with code. Anyone can help me? Thanks.
My firebase data looks like this. I want to access the data of salon->1 I can access that -
databaseReference = mDatabase.child("salon").child("1").child("franchises");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But in this case the data is not secure cay body can ready write data so I try to add a rule like this -
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid",
".read": "$uid === auth.uid"
}
}
}
}
But now I am getting permission denied in android when I try to access the data. What I am doing wrong?
The default behavior when nothing is specified is that a user is not allowed to read data. You're not setting any permission on salon, so Firebase rejects the read.
To grant read permission, you'll have to also specify who can read the data under the salon node. For example, to allow users to read all salon data:
{
"rules": {
"salon": {
".read": "auth != null"
}
},
"users": {
"$uid": {
".write": "$uid === auth.uid",
".read": "$uid === auth.uid"
}
}
}
}
My firebase database is something like this:-
these are the security rules i have written but when i use them in simulator they validate just fine, but when used in code, give permission denied error
{
"rules": {
"jokes" : {
"textjokes" : {
".read" : true,
".write": "auth != null"
}
},
"users": {
"$uid": {
".write": "$uid == auth.uid"
}
},
"userslikelist": {
"$uid": {
".write": "$uid == auth.uid"
}
}
}
}
I get error:-
/userslikelist/qzCqJph6XcZbiIpbDKTTxwjRHrh1/-KK850oXwPnOvxan1xNG failed: FirebaseError: Permission denied
/jokes/textjokes/MISC-0-01/likeCount failed: FirebaseError: Permission denied
My code:-
Firebase ref = new Firebase("https://xxxxxxxxx.firebaseio.com/userslikelist/" + mAuth.getCurrentUser().getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(!likedMap.containsKey(postSnapshot.getKey())){
likedMap.put(postSnapshot.getKey(), postSnapshot.getValue(String.class));
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
I dont get it. what am i doing wrong?
Updated Code:-
{
"rules": {
"jokes": {
"textjokes": {
".read": true,
".write": "auth != null"
}
},
"users": {
"$uid": {
".write": "$uid == auth.uid"
}
},
"userslikelist": {
"$uid": {
".read": "$uid == auth.uid",
".write": "$uid == auth.uid"
}
}
}
}
You are not giving read access to /userslikelist/userId so you wont be able to get dataSnapshot on your onDataChange.
Make sure to set a read permission on the /userslikelist/userId level.
{
"rules": {
"jokes" : {
"textjokes" : {
".read" : true,
".write": "auth != null"
}
},
"users": {
"$uid": {
".write": "$uid == auth.uid"
}
},
"userslikelist": {
"$uid": {
".read": "$uid == auth.uid", //do whatever logic you need here
".write": "$uid == auth.uid"
}
}
}
}
For anyone else who is having this problem. The issue here was that i was using the legacy firebase api methods to set values and read from database. I changed the method of updating to use the new google firebase system as used in this example and now i can update the database.
https://github.com/firebase/quickstart-android/blob/master/database/app/src/main/java/com/google/firebase/quickstart/database/NewPostActivity.java#L39-L39