Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Last active November 4, 2024 03:22
Show Gist options
  • Save codediodeio/6dbce1305b9556c2136492522e2100f6 to your computer and use it in GitHub Desktop.
Save codediodeio/6dbce1305b9556c2136492522e2100f6 to your computer and use it in GitHub Desktop.
Common Database Rules for Firebase
// No Security
{
"rules": {
".read": true,
".write": true
}
}
// Full security
{
"rules": {
".read": false,
".write": false
}
}
// Only authenticated users can access/write data
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
// Checks auth uid equals database node uid
// In other words, the User can only access their own data
{
"rules": {
"posts": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
// Validates user is moderator from different database location
{
"rules": {
"posts": {
"$uid": {
".write": "root.child('users').child('moderator').val() === true"
}
}
}
}
// Validates string datatype and length range
{
"rules": {
"posts": {
"$uid": {
".validate": "newData.isString()
&& newData.val().length > 0
&& newData.val().length <= 140"
}
}
}
}
// Checks presense of child attributes
{
"rules": {
"posts": {
"$uid": {
".validate": "newData.hasChildren(['username', 'timestamp'])"
}
}
}
}
// Validates timestamp is not a future value
{
"rules": {
"posts": {
"$uid": {
"timestamp": {
".validate": "newData.val() <= now"
}
}
}
}
}
// Prevents Delete or Update
{
"rules": {
"posts": {
"$uid": {
".write": "!data.exists()"
}
}
}
}
// Prevents only Delete
{
"rules": {
"posts": {
"$uid": {
".write": "newData.exists()"
}
}
}
}
// Prevents only Update
{
"rules": {
"posts": {
"$uid": {
".write": "!data.exists() || !newData.exists()"
}
}
}
}
// Prevents Create and Delete
{
"rules": {
"posts": {
"$uid": {
".write": "data.exists() && newData.exists()"
}
}
}
}
@aniketmlk6
Copy link

good job

@TannoFinn
Copy link

Thank you so much! Still one thing I dont understand - how can I combine these in one expression? I want users to only access their own posts but being able to delete them. At the moment this does not allow my users to "remove" posts, instead it throws an permission error. Shouldn't it work anyway as $uid === auth.uid gets true and there is no other literal to it?

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

@sebastiandg7
Copy link

@TannoFinn maybe a little late but... you can use ".delete" also

@Uroos
Copy link

Uroos commented Feb 17, 2019

Thanks a lot. One single goto place for all the basic and most commonly used rules.

@blu94
Copy link

blu94 commented Feb 22, 2019

may i know how to edit database data through POSTMAN or http request after apply the rules??

@ziarv
Copy link

ziarv commented Apr 2, 2019

can you please provide a sample of using unique fields in a collection

@muankit
Copy link

muankit commented Jan 14, 2020

I am registering user using google sign in and on successful sign in saving user email and name in database .
This rule is working fine :

{
       "rules": {
              ".read": "auth != null",
              ".write": "auth != null"
        }
   }

but i want to use this rule :

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

but it is saying permission denied .

My Firebase Database Structure looks like this :

     MAIN_NODE 
               |
               -  Users
                     |
                     - UID1
                          |- NAME : USERNAME
                          |- EMAIL : USER_EMAIL
                     - UID2
                          |- NAME : USERNAME
                          |- EMAIL : USER_EMAIL
                     - UID3
                          |- NAME : USERNAME
                          |- EMAIL : USER_EMAIL

What should i change in these rules to get permitted to write and read ?

@asterixorobelix
Copy link

Is there a way to prevent reads for anyone other than my app, using the android applicationID?

@bulatgab
Copy link

bulatgab commented Feb 18, 2020

This doesn't seem to be correct (checking if the user is a moderator):
".write": "root.child('users').child('moderator').val() === true"

Shouldn't it be this way?
".write": "root.child('users').child('moderator').child(auth.uid).exists()"

@chirag-jn
Copy link

chirag-jn commented Apr 21, 2020

Rule to allow only the admin accounts to make an update to the database while allowing global reading access:

{
  "rules": {
    ".read": true,
    ".write": false
  }
}

@rishi615
Copy link

rishi615 commented May 16, 2020

Hello. @codediodeio
I am creating an application where the users should be able to read the posts and also comment on the posts.
They should also be able to delete or edit their own comments.

However, only the admin should be allowed to make, edit, and delete the posts.
Also, all of my users are required to sign-in in the application.
Please tell me what rules should I set.

@sandydebug
Copy link

may i know how to edit database data through POSTMAN or http request after apply the rules??

You need authenticate using email password by giving them in header fields of the post request and then post data to be updated in json format.

@dchattar
Copy link

you are awesome. thanks

@Shaunmax
Copy link

Shaunmax commented Jul 13, 2020

// Validates timestamp is not a future value

{
  "rules": {
    "posts": {
       "$uid": {
         "timestamp": { 
           ".validate": "newData.val() <= now" 
         }
       }
     }
   }
}

Is it possible to set a rule for timestamp which will check if the timestamp is <= now && >= (now - 1 hours).
i.e i dont want to allow any writes which was posted an hour ago!

@ChrisMcG2020
Copy link

I am using these rules at present
{
"rules": {
"Users":{
"$uid":{
".read":"auth != null",
".write": "auth != null && auth.uid == $uid",
}
},
}
}
I want the any authenticated user to see the info while any profile updates should be carried out by the person with the authorised UID. When I run this the access to the read is denied logcat says permission denied

Listen at /Users failed: DatabaseError: Permission denied
and I have a profile page in my app and all the info is blank. However if I click into the info to edit it it will update and display it in the app. Also If I remove the "Users" part from the rules I can see the info but cannot update. Any ideas what the issue is I want to use these rules and all documentation/videos seem to suggest this approach but cannot get them implemented. Also in the rules playground , I can get the read at the path, with the authenticated UID to pass

@adelelzeiny
Copy link

How to make some users see posts and i added them by uid

@hatimmts
Copy link

what if I want to make an if statment in rules , How?
for example
user can write in "MyRequests" child if his authUid = (saved Uid in "MyFollowers" child)

@deflexable
Copy link

what if I want to make an if statment in rules , How?
for example
user can write in "MyRequests" child if his authUid = (saved Uid in "MyFollowers" child)

@hatimmts you can use "( )" to make an if statement in rules, this is really useful when dealing with "| |",

this basically group the rule into a separate unit but all your command are executed at once no matter how you nest the "( )".

you can use root, newData, data, parent(), child() to navigate through different nodes in the database.

@NaqiControl
Copy link

NaqiControl commented May 5, 2021

@visalsen
Copy link

visalsen commented Jul 5, 2021

Can you help me? I'm newer so I don't know in deep of this problem. When I used this:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
It's doesn't worked. It appear a message 401 (Unauthorized)
It worked only for:
{
"rules": {
".read": true,
".write": true
}
}

@sandydebug
Copy link

Only if you authenticate the user , the access is given .Like you need to perform firebase authentication using email password or mobile signin or any other method and then try to access the database .

@ajlanga
Copy link

ajlanga commented Mar 4, 2022

This doesn't seem to be correct (checking if the user is a moderator): ".write": "root.child('users').child('moderator').val() === true"

Shouldn't it be this way? ".write": "root.child('users').child('moderator').child(auth.uid).exists()"

@bulatgab - Were you able to get this to work? I've tried this but keep getting 401 errors.

@koddek
Copy link

koddek commented Sep 12, 2022

Hi all. I am using the Firebase rest API to read/write to Firebase real-time database. e.g. "[path-to-db].json".
How do I set the db rules to be able to freely read from the database, while needing to pass an auth password in URL to be able to write to the database? e.g. "[path-to-db].json?auth=[some-password]"

@capscode
Copy link

Nice one, thanks for this...

JUST 2 DOUBT, any help will be highly appreciated.

// Checks auth uid equals database node uid
// In other words, the User can only access their own data
{
"rules": {
"posts": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}

DOUBT-1
In the above security rule,
the current logged in user can be able to access (read/write) their node/data.
is my understanding correct??

DOUBT-2
and how can i achieve that when the admin of this firebase logged in, then the admin can be able to write, and other user will not be able to access any write operation???

@AlexSloo157
Copy link

hi i want know .. how i created key and i cant delet it only . or update . without is child"data"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment