0

I'm trying to retrieve data from a firebase database, but to secure the data I should give the API the user's id, and it should answer with the user's name.

Here is my database format:

users : {
"x0001": "John"
"x0002": "Samuel" 
"x0003": "Rachel"
}

And Here are the constraints respecting the documentation https://firebase.google.com/docs/database/security/securing-data

  {
  "rules": {
    "users": {
        ".read": "query.equalTo != null",
        ".write": false
      }
  }
}

Here is the method to access to my database

func isUserExists(userId: String) {     
     Database.database().reference().child("users")
                .queryOrderedByKey()
                .queryEqual(toValue: userId)
            .observeSingleEvent(of: .value, with: { (snapshot) in
                print(snapshot.value as? String)

            }){ (error) in
                print("error: \(error.localizedDescription)")
           }
}

When I call this method for example with a userId

isUserExists(userId: "x0001") 

output

error : Permission Denied

When I test with no constraints it works well, so I guess the request is well written but it does not respect this constraint

".read": "query.equalTo != null"

Thanks

Omaty
  • 425
  • 5
  • 14
  • Please limit yourself to one question per post, as the two you now posted have complete separate answers. For #2: you can't **return** something that is asynchronously read. The typical solutions are to either [use GCD](https://stackoverflow.com/q/44050673) or [pass in a custom closure](https://stackoverflow.com/a/37106829). – Frank van Puffelen Mar 26 '20 at 14:43
  • thank you Fank I will edit the post to keep one question onlyt – Omaty Mar 26 '20 at 15:00
  • Can you print the value of `uid` right before you run the query, and then edit your question to include (only) the updated code and its output? – Frank van Puffelen Mar 26 '20 at 16:10
  • @FrankvanPuffelen I changed the real data for this post, but in this case I call for example the function isUserExists(userId: "x0001") – Omaty Mar 26 '20 at 16:18
  • In that case I don't immediately see what's wrong. Can you add a `query.orderByKey` to your rules to see if that helps? So `query.orderByKey && query.equalTo != null` – Frank van Puffelen Mar 26 '20 at 16:56

0 Answers0