Stanislav Putilov
Stanislav Putilov

Reputation: 185

Firebase Realtime Database rules for specific node of structure

Before creating a new user I want to check if creating username property already exists in Firebase Database.

Checking function is:

let databaseRef = Database.database().reference()
databaseRef.child("users").queryOrdered(byChild: "username").queryEqual(toValue: loginRegisterTextField.text).observeSingleEvent(of: .value, with: { (snapshot: DataSnapshot) in
   if snapshot.exists() {
       print("Login exists") 
   } else {
       print("Login does not exist")
  }
})

JSON is:

enter image description here

Rules are for node users:

{
  "rules": {
        
    "users" : { 
      ".read": "auth != null",

          "$uid" : {
            ".write": "auth != null && auth.uid == $uid",
        }
    },

Is it possible to write a rules to check existing of username without a new uid?

Upvotes: 0

Views: 276

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598887

There is no way to check for a specific value across a JSON branch in security rules. This has been covered quite a few times before, so I recommend checking some of these search results.

But you can make your query on /users more secure, by only allowing that specific query, and not allowing people to read all of /users. To secure the query you could some something like:

{
  "rules": {     
    "users" : { 
      ".read": "auth != null && 
                query.orderByChild == 'username' &&
                query.equalTo !== null",
      ...

This is the first time I've used query.equalTo !== null, so there may be some small mistakes in that part, but the flow should be clear.

Upvotes: 1

Related Questions