Firebase Database Rules

2 min. read

Firebase Database Security Rules

The Firebase Database has a rules language, called the Security Rules.

Rule Types

.read
.write
.validate
.indexOn

Read Rule

Write Rule

Validate Rule

If validation fails, data is not saved.

Example:

1
2
3
4
5
6
7
8
9
10
{
"rules": {
"users":{
“$uid”:{
“.validate”: “newData.child(‘firstName’).isString() &&
newData.child(‘dob’).isNumber()”
}
},
}
}

IndexOn Rule

Default Rules

{
“rules”: {
“.read”: “auth != null”,
“.write”: “auth != null”,
“users”:{
“.indexOn”: “email”
},
“accounts”:{
“.indexOn”: “email”
}
}
}

{
“rules”: {
“.read”: “auth != null && root.child(‘users/‘ + auth.uid + ‘/roles/admin’).val() == true”,
“.write”: “auth != null && root.child(‘users/‘ + auth.uid + ‘/roles/admin’).val() == true”,

"categories": { ".read": true } ,
"tagList": { ".read": true } ,
"users": {
  "$uid": {
   ".read": "auth != null && $uid == auth.uid",
    "roles": { ".write": false },
    "questions": { ".write": "auth != null && $uid == auth.uid" }
  }
},
"questions": {
  "published": { ".read": true },

“unpublished”: {
“$question_id”: {
“.read”: “auth != null && data.child(‘created_uid’).val() == auth.uid”,
“.validate”: “newData.child(‘created_uid’).val() === auth.uid”,
“.write”: “auth != null && ((data.exists() &&
data.child(‘created_uid’).val() == auth.uid &&
data.child(‘status’).val() != 2)
||
(!data.exists() &&
newData.child(‘created_uid’).val() == auth.uid))”
}
}
}
}
}

Pagination
https://howtofirebase.com/collection-queries-with-firebase-b95a0193745d

Learning Firebase Security Rules

Understanding Firebase Security Rules

References

https://angularfirebase.com/lessons/role-based-permissions-and-authorization-with-firebase-auth/

https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3

3 R Rules (Rules, Roles and routes)
https://blog.realworldfullstack.io/real-world-angular-part-6-3rs-rules-roles-routes-9e7de5a3ea8e

https://blog.realworldfullstack.io/real-world-angular-part-1-not-another-todo-list-c2ea5020f944

Admin Guard
https://angularfirebase.com/lessons/role-based-authorization-with-firestore-nosql-and-angular-5/

https://firebase.google.com/docs/database/security/quickstart

Securing Data
https://firebase.google.com/docs/database/security/securing-data