简体   繁体   中英

Firebase DatabaseError: Permission denied

I want to save some data on Items node in firebase. i was able to save when my rule was

"Items":{
   ".write": "auth != null",
   ".read": "auth != null"
}

but i want users to write/update their own items and i don't want to use $ variable since it will add some data on my path. that is

the below method will add some data on my path instead of /Items it will be /key/Items

{


"rules": {
    "Items": {
      "$user_id": {
        ".read": "auth != null",
        ".write": "$user_id === auth.uid"
      }
    }
  }
}

Therefore, the best method that i saw was to write my rule like this

"Items":{
       ".read": "auth != null",
        ".write": "(data.exists() && data.child('userId').val() === auth.uid) || (!data.exists() && newData.child('userId').val() === auth.uid)"

}

}

When i run the below code on the simulator, everything is ok

 {
"userId":"xxxxxxxxxxxxxxxxx"
}

But wnen i try to upload data from my phone, i get an error

setValue at /Items/-KWH6tgdLPGTdascf-w3 failed: DatabaseError: Permission denied

Where am I going wrong?

A simpler way is to just check whether the id of logged in user is the same as id stored by userId variable before allowing the user to update and push the object to firebase.

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Item item;
if (user != null) {
   //logged in
   String uid = user.getUid();
   if(uid.equals(item.getUserId()){
    //allow the user to update item.
   }
} else {
  //not logged in
}

set database read-write rules to true

"Items":{
   ".write": "true",
   ".read": "true"
}

As per last verion of realtime datebase, tr this: https://firebase.google.com/docs/firestore/security/get-started?authuser=0

Add this on ur tab rule at Database:

    // Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM