How to set firebase rules based on database user id (not uid)

1.7k views Asked by At

Hi I have a list of users in my fb database. The user id is auto-generated after successful registration and each user entry has the name, email, and uid. Also, each of these properties is being indexed in /index so that I can easily look up a user's id given their uid.

According to the docs, firebase says to use write: $user_id === auth.uid

How can I accomplish this using the generated ID instead of the uid?

here's the fb db: https://medviz.firebaseio.com/

1

There are 1 answers

9
A.B On BEST ANSWER

In Your users object there will be users like this

users : {
 user1234abc:{         
       name: "abc"         
    },                    
    user2434dbcc:{         
       name: "abc"         
    } 
}   

you will have many unique key/user nodes in users object, eg user1234abc, user2434dbcc

That unique key can be named any variable in rules it not necessary to call it $user_id, you can call it anything you want for example you can name the variable as $any_variable for unique user keys

and in auth.id whenever user successfully authenticate that same unique id is in auth.uid so you can any where math that auth.uid when you are editing the info related to that user

For example if auth.uid contains user1234abc and if user1234abc is editing this object user1234abc:{name: "abc" } thn accordind to .write rule he will be able to

See the updated view below

Updated Visual Hierarchy:

--schema--
users : {
           ________________
          |
    user1234abc:{          |
       name: "abc"         |  
    },                     |
    user2434dbcc:{         |
       name: "abc"         |
    }                      |
}                  key can be name as any variable  in rules
                           |
-- rules--
                           | 
{                          | 
  "rules": {               |
    "users": {             |
      ".read": true,       |
           ________________|___________  
          |                            |
         \|/                           | 
      "$any_variable": {              \|/     
        ".write": "$any_variable === auth.uid"
      }
    }
  }
}