Write and Read in Firebase Android - android

I am using Firebase Realtime database with the below rules
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
My code to write in database is
mDatabase = FirebaseDatabase.getInstance().getReference("OWNER_DATA");
String id = mDatabase.push().getKey();
OwnerSignup ownerSignup = new OwnerSignup(id, name, email, phoneNumber);
mDatabase.child("MY_DATA").setValue(ownerSignup);
If I change the rules to
read:"false"
write:"false"
I can push the data but with the above rules I cannot insert values in the data.
Please help me to resolve this issue.
and how can I call this with API in Postman where my API is
"https://rent-c-246c0.firebaseio.com/"
I tried to do this in postman with the below given API
https://rent-c-246c0.firebaseio.com/OWNER_DATA.json
here I want to pass my auth.uid token

If you use the following rules:
read:"false" and write:"false"
It means you cannot retrieve nor add data to the database.
If you use:
{
"rules": {
"some_path": {
"$uid": {
// Allow only authenticated content owners access to their data
".read": "request.auth.uid == uid"
".write": "request.auth.uid == uid"
}
}
}
}
Then these rules restrict access to the authenticated owner of the content only. The data is only readable and writable by one user, and the data path contains the user's ID.
https://firebase.google.com/docs/rules/basics#content-owner_only_access

Related

Firebase Realtime Chat Rules

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

how can I read and write as an admin even if the rules set to false in Firebase Realtime Database

As an admin I am trying to get the users data so that I could 'read' and 'write' even through the rules of the firebase 'read','write' set to be false.
users
|
"uid"
|-firstname: "xyz"
|-lastname: "xyz"
|-email: "xyz#gmail.com"
Here, is my rules
"users": {
"$uid": {
".read": "auth != null && $uid === auth.uid",
".write": "auth != null && $uid === auth.uid"
}
}
when I am retrieving users data from firebase using FirebaseRecyclerOptions, users data display only when I set rules read and write to true but I want even if the rules set to be false through admin I could read and write. Is this possible
FirebaseRecyclerOptions<Model> options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(FirebaseDatabase.getInstance().getReference("Users"), Model.class)
.build();
Add a boolean to your user object and call it admin, set it false for all the users except you.
Now copy that to your firebasee rules:
"users": {
".read":
"root.child('users').child($uid).child('Admin').val()",
".write":"
"root.child('users').child($uid).child('Admin').val()"
,"$uid": {
".read": "auth != null && $uid === auth.uid",
".write": "auth != null && $uid === auth.uid"
}
}
}
}
Just like the isActivated boolean I have in my Users you can create a boolean called isAdmin.Add it to your admin class , give it set and get methods in your class.When you upload it to firebase you can read and write this data.
Then let your firebase rules to do the job.
It depends on what "as an admin" means to you. If the application administrator is only you for example, you could simply hard-code your own UID in the security rules:
"users": {
".read": "auth.uid === 'yourOwnUid'"
"$uid": {
".read": "auth != null && ($uid === auth.uid",
".write": "auth != null && $uid === auth.uid"
}
}
This grants the one user access to all of /users, while everyone else can only read their own child node under that path.
Hard-coding the UID like this works great during development, as you're likely the only administrator. Later on when closer to release, you'll want to store a list of administrator UIDs in the database:
"Admins": {
"yourOwnUid": true,
"otherUid": true
}
You can then check in your rules whether the current user's UID exists in this path with:
"users": {
".read": "root.child('Admins').child(auth.uid).exists()"
...
}

real-time database in firebase, rules

I have the following problem: I have my app in development, this allows the authenticated user to add data from a crud, in the rules of firebase real-time database, when they are in "true" read and write, they are saved and visualized, but when I try to add the following rule it does not save the data
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"some_path": {
"$uid": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "auth.uid == $uid"
}
}
It is supposed to be so that the authenticated users can read and write their data, but that the other users can only see the published data. I cannot let users modify the data of others.
Change some_path with your refrence name
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"some_path": {//change this with your ref_name
"$uid": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "auth.uid == $uid"
}
}
}
}

W/SyncTree: Listen at /Products failed: DatabaseError: Permission denied?

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.

Firebase Real Time Database rules

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.

Categories

Resources