I am trying to base a security rule on a reference to another object.
I have a collection of users and collection of roles. A user object has a field called "role" that is a reference to a particular document in the roles collection.
users
id
name
role <-- reference to particular role
roles
id
name
isSuperUser
The goal here is to allow a user with a particular role (the role with isSuperUser == true) to edit any other role or it's sub-collections;
Here are my rules that I would have thought would have worked:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
allow read, write: if request.auth.uid == userId;
}
match /roles/{roleId=**} {
function isSuperUser() {
return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role.isSuperuser == true;
}
allow read: if request.auth.uid != null;
allow write: if isSuperUser();
}
}
I have confirmed the following works, but it's not really that useful...
get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role != null;
If there is a better way to accomplish role base security, I am all ears.
The lack of any debugging tools makes this quite frustrating.
I know it's been a while since the original question but I've had a similar issue and I hope this could help you or others.
Your condition is:
get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role.isSuperuser == true;
But role is a reference, which (apparently) means you need to get it as well. Try this:
get(get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role).data.isSuperuser == true;
Have you tried to move the wildcard to a nested path?
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
match /{role=**} {
allow read: if request.auth.uid != null;
allow write: if isSuperUser();
}
}
}
}
Related
I've a firestore database and I now need to add a new collection.
Each entry of this collection should contain:
Which userId is the owner(field admin)
Which userId has been allowed to edit this element(field writer)
Which userId has been allowed to only read(field reader).
I'm currently only at the first step, and already strugling:
I was hoping to be able to query my collection( /trips/) and get only the one that I'm allowed to access, but I get an error:
FirebaseError: Missing or insufficient permissions.
Here is my rules file:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null;
}
match /trips/{trip} {
allow read, update, delete: if request.auth != null && request.auth.uid == resource.data.admin;
allow create: if request.auth != null;
}
}
}
So my questions:
Is this the correct way of managing resource that must be acceeded by multiple people(meaning, I cannot just have the userId in the path since there are multiple users)
How should I query only the documents list that I'm allowed to see?
Thank you very much for your help
As you will read in the doc, "All match statements should point to documents, not collections".
With
service cloud.firestore {
match /databases/{database}/documents {
match /trips {
// ....
}
}
}
you don't point to a document. You should use a wildcard to point to any document in the specified path, as follows:
service cloud.firestore {
match /databases/{database}/documents {
match /trips/{trip} {
// ....
}
}
}
Therefore the following should correctly implement your requirements:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /trips/{trip} {
allow read: if request.auth != null &&
(request.auth.uid == resource.data.admin
|| request.auth.uid == resource.data.writer
|| request.auth.uid == resource.data.reader
);
allow update: if request.auth != null &&
(request.auth.uid == resource.data.admin
|| request.auth.uid == resource.data.writer
);
allow create: if request.auth != null;
}
}
}
Then, for the two questions:
Is this the correct way of managing resource that must be acceeded by multiple people (meaning, I cannot just have the userId in the path
since there are multiple users)
If the admin, writer and reader are specific for each document, yes this is the correct way. If those roles would be more global (e.g. all the trips to Europe can be edited by the same user), you could use a role based approach with Custom Claims.
How should I query only the documents list that I'm allowed to see?
It is important to note that rules are not filter. So your query for getting docs needs to be aligned with the rules. In your specific case, you could have an additional field of type Array which contains three values; the uids of the admin, writer and reader, and use the array-contains operator. Something like:
const user = firebase.auth().currentUser;
const query = db.collection("trips").where("authorizedReaders", "array-contains", user.uid);
match /{document=**} {
allow read, write: if false;
}
You don't need the above code as it will apply to all routes of the database, because of the above line you are getting the below error as it does not allow you to read and write to the database
FirebaseError: Missing or insufficient permissions.
Now, if you want to assign privileges to users then you should add the Role field to users collections which would have a value such as Admin, Editor, Reader
Then, you can check in routes something like below
match /users/{userId}/trips/{tripId} {
allow read, delete: if request.resource.data.role == "Admin";
allow create, update: if request.resource.data.role == "Admin || request.resource.data.role == "Editor";
}
If you want to know more about how to create a route check out this video for the best explanation
I have a collection structure like this.
products {
123456 : {
stock_qty : (Number)
}
}
I want to validate stock quantity to be positive. I have applied following firebase security rule.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if request.auth.uid != null;
allow write: if request.auth.uid != null;
}
match /products/{document=**}{
allow write: if request.resource.data.stock_qty > 0;
}
}
}
But Still I am able to add products with negative stock_qty.
what I am doing wrong here?
You need to remove this part of your rules:
match /{document=**} {
allow read: if request.auth.uid != null;
allow write: if request.auth.uid != null;
}
This allows all authenticated users to read and write your entire database, regardless of any other rules you have defined.
If any rule gives access to a document, another rule cannot revoke that access.
If you have other queries for other collections that must be protected, you will need rules for those other collections as well.
I'm trying to use a wildcard in my firebase security rules but it's not working like the online documentation describes.
I want to return the entire itineraryList collection but the security rules aren't working.
match /itinerary/{userId=**}/itineraryList/{doc} {
allow read: if request.auth.uid == userId;
allow write: if request.auth.uid == userId;
}
What is the correct syntax here to give authenticated users access to the entire list?
Update following your comments:
If you want to give read access to any authenticated user to all documents under the itinerary collection (including sub-collections), do as follows:
service cloud.firestore {
match /databases/{database}/documents {
match /itinerary/{docId=**} {
allow read: if request.auth.uid != null;
}
//possibly add another rule for write
}
}
Initial answer:
This is because by doing {userId=**} you are using the "recursive wildcard syntax", see https://firebase.google.com/docs/firestore/security/rules-structure#recursive_wildcards. It will correspond to the "entire matching path segment".
You should do:
service cloud.firestore {
match /databases/{database}/documents {
match /itinerary/{userId}/itineraryList/{doc} {
allow read: if request.auth.uid == userId;
allow write: if request.auth.uid == userId;
}
}
}
You may also watch this official Firebase video about Firestore security rules, it explains this point, among others: https://www.youtube.com/watch?v=eW5MdE3ZcAw
I use a collection called "admin" in Firestore to define which users can write new documents (image below).
At moment, it is controled just by software. I would like to add rules to Firestore. I tried the rule below but it didn't work. What would be the correct rules in that case ?
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if request.auth != null;
allow write: if get(/admin/{anyDocument}).data.userId == request.auth.uid;
}
}
}
I'd recommend instead having a users collection with an admin field that can be set to true/false. Then you can do something like:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if request.auth != null;
allow write: if get(/users/${request.auth.uid}).data.admin == true;
}
}
}
As far i know this is not possible with your current database structure. Because the push key is not accessible in firestore rules unless it is with in the admin node.
One way is to save the admin with their uid as key like admin/userID/data...
now you can access it
allow write: if get(/databases/$(database)/documents/admin/$(request.auth.uid)).data.userId == request.auth.uid;;
The solution is in the end of the post. Check it out.
Решение проблемы в конце поста. Дочитайте.
just a simple question: whats wrong with this and why this is not working?
Trying to get access with user who has role 'admin' in users section to the /titles/{anyTitle} but still get
Missing or insufficient permissions.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow write: if false;
allow read: if false;
}
function userCanWrite () {
return get(/databases/{database}/documents/users/$(request.auth.uid)).data.role == "admin";
}
match /titles/{anyTitle=**} {
allow read: if request.auth != null;
allow write: if userCanWrite();
}
}
}
Here is my database structure
P.S.
I tried another rule from official documents
get(/databases/{database}/documents/users/$(request.auth.uid)).data.isAdmin == true;
and this is not working too
UPDATE: CORRECT WAY TO DO IT
Support helped me find the solution
this is how you should do:
db structure:
users -> {{ userid }} -> { role: "admin" }
database rule settings:
get(usersPath/$(request.auth.uid)).role == "admin" || get(usersPath/$(request.auth.uid)).data.role == "admin";
I contacted to the Firebase support to report that bug and they gave me a temporary solution on this. It seems that they are having a bug in their systems on the security rules side. They say that the documentation is ok, but for now we should workaround this way:
get(path).data.field == true || get(path).field == true;
Because the bug is that data object isn't populated, you should check both properties. There's no ETA for launching a solution on this bug, so I asked they if they could give me an advice when they solved this issue, so I'll keep this answer up-to-date with their information.
So the way I've solved it is I've created another Collection Called admins
Then I've just added the uid of the user I needed there as such -
Here is my database structure - https://i.imgur.com/RFxrKYT.png
And here is the rules
service cloud.firestore {
match /databases/{database}/documents {
function isAdmin() {
return exists(/databases/$(database)/documents/admins/$(request.auth.uid));
}
match /tasks/{anyTask} {
allow read: if request.auth != null;
allow create: if request.auth != null;
allow update: if request.auth != null && isAdmin();
allow delete: if request.auth != null && isAdmin();
}
}
}
You can view my full Open Source project here:
https://github.com/metaburn/doocrate
You should use $(database) instead of {database} in your code:
get(/databases/{database}/documents/users/$(request.auth.uid)).data.role == "admin";
What worked for me was moving the userCanWrite function above my rules. It appears that the function has to be defined before any of the match rules that call it. Maddening :-)
This is the Firestore rule I use to check if the user is admin.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if userIsAdmin();
}
function userIsAdmin() {
return getUserData().userRole == 'Admin';
}
function getUserData() {
return get(/databases/$(database)/documents/User/$(request.auth.uid)).data;
}
}
}