Sunil Kumar
Sunil Kumar

Reputation: 1794

How to set Firebase Realtime Database Security Rules for specific email domain and allow read write to multiple parent nodes

How to set security rules for Firebase realtime database structure as below:

users: {
...
...
...
},
books: {
...
...
...
},
sales: {
...
...
...
}

Condition: Firebase auth is set to email/password and only user logged-in with emails ending with domain [mydomain.co.in] must be able to read or write to parent node. Without using custom claims.

Adding below security rules is applied/working only for the the first parent node [users] and not to all, what is a miss here?

{
  "rules": {
    ".read": false,
    ".write": false,
    "users": {
      ".read": "auth.token.email.matches(/.*@mydomain.co.in$/)",
      ".write": "auth.token.email.matches(/.*@mydomain.co.in$/)",
      ".indexOn": "name"
    },
      
    "books": {
      ".read": "auth.token.email.matches(/.*@mydomain.co.in$/)",
      ".write": "auth.token.email.matches(/.*@mydomain.co.in$/)",
      ".indexOn": "title"
    },
    "sales": {
      ".read": "auth.token.email.matches(/.*@mydomain.co.in$/)",
      ".write": "auth.token.email.matches(/.*@mydomain.co.in$/)",
      ".indexOn": "price"
    },
  }
  
}

Upvotes: 0

Views: 1368

Answers (1)

Amod Gokhale
Amod Gokhale

Reputation: 2448

Try below enclosed within uid field? Reference https://firebase.google.com/docs/reference/security/database

same code works with auth.token.email.matches(/.*@mydomain.co.in$/)

    {
   "rules":{
    ".read": "false",
    ".write": "false",
      "users":{
         "$uid":{
            ".read":" auth.token.email.endsWith('@mydomain.co.in')",
            ".write":" auth.token.email.endsWith('@mydomain.co.in')",
            ".indexOn":"name"
         }
      },
      "books":{
         "$uid":{
            ".read":" auth.token.email.endsWith('@mydomain.co.in')",
            ".write":" auth.token.email.endsWith('@mydomain.co.in')",
            ".indexOn":"title"
         }
      },
      "sales":{
         "$uid":{
            ".read":" auth.token.email.endsWith('@mydomain.co.in')",
            ".write":" auth.token.email.endsWith('@mydomain.co.in')",
            ".indexOn":"price"
         }
      }
   }
}

Auth Token payload

{
  "token":{
     "email": "[email protected]"
  }
}

enter image description here

enter image description here

Upvotes: 0

Related Questions