I have a problem restricting access to the children of the object
The rules I need:
roles - read
-- UID
--- SUPUSR
---- settings = read only
--- store = write and read
My rules
"roles":{
".read":"auth != null",
".write":"root.child('roles/SUPUSR/').child(auth.uid).child('settings').child('pri_enabled').val() == 1 || root.child('roles/USERS/').child(auth.uid).child('settings').child('pri_enabled').val() == 1",
"settings":{
".read":"auth != null",
".write":false
}
If I leave it the way it is above, it inherits the "roles" rules for writing
Firebase Realtime Database Rules cascade, once you grant permission, you cannot revoke it. So if you allow write access on /roles, anyone can write to any child of /roles whether it's their own or someone else's data.
Other notes:
The current rules affect /roles and /roles/settings, which is too high in the database tree, you should be setting the rules of /roles/SUPUSR/someUserId, /roles/SUPUSR/someUserId/settings and so on.
The use of auth != null seems out of place. Should any logged in user be able to read any other user's roles? Should this only work for super users?
Some of the data would also make sense to be validated.
{
"rules": {
"roles": {
"SUPUSR": {
"$uid": {
// any data under /roles/SUPUSR/$uid is readable to logged in users
".read": "auth != null",
"nome": {
// only this user can update nome, it also must be a string
".write": "auth.uid === $uid",
".validate": "newData.isString()"
},
"role": {
// only this user can update role, and it must be one of a select number of string values
".write": "auth.uid === $uid",
".validate": "newData.isString() && newData.val().matches(/^(R&S|Admin|etc)$/)"
},
"store": {
".write": "root.child('roles/SUPUSR/').child(auth.uid).child('settings').child('pri_enabled').val() == 1 || root.child('roles/USERS/').child(auth.uid).child('settings').child('pri_enabled').val() == 1"
}
// any other keys are ".write": false, by default, which includes "settings"
}
}, // end /rules/roles/SUPUSR
"USERS": {
"$uid": {
...
}
}, // end /rules/roles/USERS
...
}, // end /rules/roles
...
}
}
Related
I'm trying to create a rule for create/access the FRD data based on authenticated user. But am getting an error where running the Rules Playground
What I want is, Users are creating the categories. So Users is able to only read their categories and update those categories.
Rule:
{
"rules": {
"users": {
"$uid": {
".write": "auth != null && $uid === auth.uid",
".read": "auth != null && $uid === auth.uid"
}
},
"categories": {
"$uid": {
".write": "auth != null && $uid === auth.uid",
".read": "auth != null && $uid === auth.uid"
}
}
}
}
Auth Users:
Realtime Database
Categories
Users
Categories Write function in Flutter
String uId = await userId();
final databaseRef = FirebaseDatabase.instance.ref('categories');
var data = await databaseRef.get();
var index = data.children.length;
await databaseRef.child('$index').set(<String, dynamic>{
"name": categoryBody.name,
"description": categoryBody.description,
"uid": uId,
"id": index,
});
Error
Is there anything wrong with the rules that am applying?
I tried to replicate your issue, but I can able to successfully test rules without errors.
The rules you are using are for authenticated users but you are testing for unauthenticated users. Means you have not enabled Authenticated field.
And you have to enter /categories/uid instead of /categories under the location and you should enter uid under Firebase UID field. You may have look at below screenshot.
You can refer this tutorial for more information.
When you're using the following security rules:
"categories": {
"$uid": {
".write": "auth != null && $uid === auth.uid",
".read": "auth != null && $uid === auth.uid"
}
}
It means that you allow the user to write/read to/from every child that exists under your categories/$uid node. So when you try to apply those rules to your actual database structure, it's the expected behavior to see that Firebase servers reject the operations since it doesn't find any $uid level in your database schema. To solve this, you have to remove that extra $uid level from rules like this:
"categories": {
".write": "auth != null",
".read": "auth != null"
}
And this is because those category objects exist directly under the categories node and not under categories/$uid.
I have a mobile application which reads the data from the firebase server without firebase login/authentication (posts and news) and I want to create an admin webpage where I can log in and add, or modify news, so I need a write permission there. My rules are currently:
{
"rules": {
".read": true,
".write": "auth !== null && ?????
}
}
Can I write something like "user.emailAddress == 'mail#example.com'"?
You can create a users table on database like
{
"users":{
"your UID":{
"isAdmin": true
}
}
}
Then edit rules :
{
"rules": {
".read": true,
".write": "auth.uid != null && root.child("users").child(auth.uid).isAdmin === true"
}
}
You might want to start by reading the documentation about securing user data. There is a lot to know here.
One possibility is using the known user's uid to restrict access. The auth.uid variable contains the uid.
".write": "auth.uid == 'the-known-uid'"
Also you can use auth.token to access some other things about the user, including email address (which may not be present):
".write": "auth.token.email == 'the#email.address'"
You can also use custom authentication tokens, which also is covered in the documentation.
Create database:
{
"users":{
"your UID":{
"isAdmin": true
}
}
}
Set rules:
Wrong:
{
"rules": {
".read": true,
".write": "auth.uid != null && root.child("users").child(auth.uid).isAdmin === true"
}
}
Right:
{
"rules": {
".read": true,
".write": "auth.uid != null && root.child('users').child(auth.uid).child('isAdmin').val() === true"
}
}
This is my DB structure
"tasks"
"$taskId"
...
"user": "firebase user id"
I have already written a rule ".read": data.child('user').val() === auth.uid" under $taskId. When I try to access a single task, this rule is taking effect.
Will this also guarantee that if I write a query like firebase.database().ref('/tasks').orderByChild('status').limitToFirst(1) I'll only get tasks that have user id field as auth.uid. Or should I also write a .read clause under tasks
There are several aspects to be answered in your question:
1/ At which level should you write the security rules?
If you write only at the task level like just follows, you will not be able to query the entire set of tasks.
You can test it by doing the following:
Rules:
{
"rules": {
"tasks": {
"$taskID": {
".read": "auth != null",
".write": "auth != null"
}
}
}
}
JS:
var db = firebase.database();
var ref = db.ref('tasks');
firebase.auth().signInWithEmailAndPassword("....", "....")
.then(function(userCredential) {
ref.once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val());
});
});
});
This will fail with "Error: permission_denied at /tasks: Client doesn't have permission to access the desired data."
If you change var ref = db.ref('tasks'); to var ref = db.ref('tasks/123456'); (123456 being an existing task id) you will get a result.
If you change your rules to the following, the two previous queries will work.
{
"rules": {
"tasks": {
".read": "auth != null",
".write": "auth != null"
}
}
}
2/ How should you do to only get tasks that have user id field as auth.uid?
The first point to note is that "Rules are not Filters", as detailed here: https://firebase.google.com/docs/database/security/securing-data#rules_are_not_filters
So if you implement security rules as follows:
{
"rules": {
"tasks": {
"$taskId": {
".read": "auth != null && data.child('user').val() === auth.uid",
".write": "auth != null"
}
}
}
}
You will need to write a query that includes the same restriction on the user uid, like the following:
var db = firebase.database();
firebase.auth().signInWithEmailAndPassword("....", "....")
.then(function(userCredential) {
var ref = db.ref('tasks').orderByChild('user').equalTo(userCredential.user.uid);
ref.once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val());
});
});
});
But this query will not work, again, because "Error: permission_denied at /tasks: Client doesn't have permission to access the desired data."
You cannot do the following neither, since "Shallower security rules override rules at deeper paths.":
{
"rules": {
"tasks": {
".read": "auth != null",
".write": "auth != null"
"$taskId": {
".read": "auth != null && data.child('user').val() === auth.uid",
".write": "auth != null"
}
}
}
}
One solution is to use Query-based Rules (see the doc here) and write your rules as follows:
{
"rules": {
"tasks": {
".read": "auth != null &&
query.orderByChild == 'user' &&
query.equalTo == auth.uid",
".write": "auth != null"
}
}
}
However, as you have probably noticed, this will prevent you to order your query (and filter it) by something else than the user (e.g. by status), since "You can only use one order-by method at a time."
The solution would therefore be to create a second data structure in parallel to your existing structure, where you add the user as a top node, like
"tasks"
"$taskId"
...
"user": "firebase user id"
"tasksByUser"
"$userId"
"$taskId"
...
You would use the update() method to write to the two data structures simultaneously. See the doc here.
I gave .read: true under tasks and it is considering the rules written under the individual task objects before returning the results.
I need to set up database rules to prevent certain sub-nodes from being accidentally deleted, but at the same time allow the sub-nodes to be added and modified. The node in question is users/[userID]. It's structured like this:
I don't want the data in users/[userID]/soundcasts to ever be deleted. And my current rules look like the following:
"users": {
".read": true,
".indexOn": "stripe_id",
"$userID": {
".indexOn": "0",
"soundcasts": {
".indexOn": "planID",
".write": "newData.exists() && auth != null",
"$soundcastID": {
".write": "newData.exists() && auth != null",
}
},
}
},
This accomplishes what I want successfully, i.e. setting users/[userID]/soundcasts to null always fails. However, since there's no .write rule on the users node itself, I'm not able to add new users to the node :(
But if I set ".write": "newData.exists() && auth != null" on the users node or the users/[userID] node, like so:
"users": {
".read": true,
".indexOn": "stripe_id",
"$userID": {
".indexOn": "0",
".write": "newData.exists() && auth != null",
"soundcasts": {
".indexOn": "planID",
".write": "newData.exists() && auth != null",
"$soundcastID": {
".write": "newData.exists() && auth != null",
}
},
}
},
it becomes possible to set users/[userID]/soundcasts sub-node to null. I'm not sure why that happens.
I need to set up the rules so that I can add new users to users node, modify any of the sub-node data under users/[userID], but prevent users/[userID]/soundcasts from being set to null.
Is that possible?
There's currently no way to set write rules to a node and another set of different rules to it's sub-node.
I would recommend creating a node soundcasts under the root node of your database to store these soundcasts, having the userID as key and have their soundcasts under each user. Then you'd be able to set your "no deletes" rule to this node:
"users": {
".read": true,
".indexOn": "stripe_id",
"$userID": {
".write": true
}
},
"soundcasts":{
".indexOn":"planID",
"$userID":{
"$soundcastID": {
".write": "newData.exists() && auth != null",
}
}
}
I've database structure like
appointments
[$userId]
[$appointmentId]
message:"something"
date:"14/12/2015"
users
[$userId]
name: Hardik
email: hardikmsondagar#gmail.com
And I'm using angularfire library of Firebase, I'm trying to restrict read operation based on uid ( means a person who created appointment only can read that). I've tried following security rule
{
"rules": {
"appointments": {
"$userId":{
"$appointmentId":{
".read": "auth.uid==$userId",
".write": true
}
}
},
"users": {
"$userId":
{
".read": "auth!=null && $userId === auth.uid",
".write": "auth!=null && $userId === auth.uid"
}
}
}
But end up on this error
Error: permission_denied: Client doesn't have permission to access the desired data.
I'm trying to access all the user's appointments using following code
var ref = new Firebase("https://<FIREBASE-APP>.firebaseio.com/appointments/"+uid);
$scope.appointments = $firebaseArray(ref);
Set rules for the $uid wildcard, to read all the children.
"appointments": {
"$uid":{
".read": "auth.uid == $uid",
".write": "auth.uid == $uid",
}
}
The $uid wildcard sets permissions for the entire list, whereas the $appointmentId wildcard sets permissions for each individual item.
But Security Rules cascade, so you only need to set the rules for the top level.
Read the docs on cascading for more information.