简体   繁体   中英

Firebase - permission denied when fetching users

I'm trying to fetch users from a Firebase database with this code but I get this error

cancel error Error Domain=com.firebase Code=1 "Permission Denied" UserInfo={NSLocalizedDescription=Permission Denied}

How should my rules be set up?

Here's the code:

FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

        print("snapshot \(snapshot)")
        //all users right here n shyt
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let user = User()

            //class properties have to match up with firebase dictionary names
            user.setValuesForKeys(dictionary)
            self.users.append(user)


            DispatchQueue.main.async {
                self.messageTable.reloadData()
            }
        }
            print(snapshot)

        }, withCancel: { (error) in
            print("cancel error \(error)")
    })

This is my rules in Firebase:

{
"rules": {
"users": {
  "$uid": {
    ".read": "$uid === auth.uid",
    ".write": "$uid === auth.uid"
  }
 }
}
}

Given your current Security rules you are only giving permission to your current user to access only its own node.

If thats the dynamic you want to go by try making another parent node which contains the details that you would wanna share with other users.

users:{
 userID1 : {../*PERSONAL DETAILS*/},
 userID2 : {../*PERSONAL DETAILS*/},
 userID3 : {../*PERSONAL DETAILS*/},
 userID4 : {../*PERSONAL DETAILS*/},
 userID5 : {../*PERSONAL DETAILS*/},
 ....
  },
USERS_INFO: {
  userID1 : {../*Details to share*/},
  userID2 : {../*Details to share*/},
  userID3 : {../*Details to share*/},
  userID4 : {../*Details to share*/},
  userID5 : {../*Details to share*/},
  ....
  }

And update your security rules to:-

 {
 "rules": {
 "users": {
   "$uid": {
     ".read": "$uid === auth.uid",
     ".write": "$uid === auth.uid"
   }
  },
  "USERS_INFO":{
     ".read" : "auth != null",
     ".write" : "auth != null"
    }
  }
 }

Query like :-

 FIRDatabase.database().reference().child("USERS_INFO").observe(.childAdded, with: { (snapshot) in

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