Database rules

Firebase database rules are the only way to secure the data. Firebase provides flexibility and expression-based rules language with JavaScript-like syntax to developers to define how your data should be structured, how it should be indexed, and when the user can read and write the data. You can also combine authentication services with this to define who has access to what data and protect your users from unauthorized access. To validate the data, we need to add a rule separately using .validate in the rules.

Consider this example:

{
"rules": {
".write": true,
"ticket": {
// a valid ticket must have attributes "email" and "status"
".validate": "newData.hasChildren(['email', 'status'])",
"status": {
// the value of "status" must be a string and length greater then 0 and less then 10
".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 10"
},
"email": {
// the value of "email" must valid with "@"
".validate": "newData.val().contains('@')"
}
}
}
}

Here are some other sample blocks of code for applying rules in the Rules tab:

Default: Rule configuration for authentication:

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

Public: These rules give full access to everyone, even people who are not users of your app. They give read and write access to your database:

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

User: These rules authorize access to a node matching the user's ID from the Firebase authentication token:

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

Private: These rule configs don't allow anyone to read and write to a database:

{
"rules": {
".read": false,
".write": false
}
}
We can also use REST API with Firebase Secret code to write and update Rules for your Firebase app by making a PUT request to the /.settings/rules.json path and it will overwrite the existing rules.

Take, for example, curl -X PUT -d '{ "rules": { ".read": true } }' 'https://docs-examples.firebaseio.com/.settings/rules.json?auth=FIREBASE_SECRET'.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset