New to Firestore security rules and is trying to understand it. I'm trying to write a security rule that allow only admins in my collection to write data and every one to read it.
The collection of admins has document ids as admin names, that is for example, "Mary Lane". Within the documents I've fields:
email: "userMailId#mail.com"
uId: "firestore_user_Id"
The uId is the id of Firestore user id. The data to write is an object Message and is:
new Message(uId, title, messageBody, timestamp)
Currently I'm trying to match the request.auth.uid with the id of the admins that are stored within the collection:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read;
allow write: if request.auth.uid == resource.data.uId;
}
}
}
Is this is write or am I doing something wrong. Any help is appreciated.
Since the admin's name is not available in this rule allow write: if request.auth.uid == resource.data.uId;, there is no way to look up the document to check it they're an admin.
You'll need a collection where you keep a document for each admin with their UID as the document key/name. Once you have that, you can check for the existence of such a document in the rule with:
allow write: if exists(/databases/$(database)/documents/admins/$(request.auth.uid));
Also see the documentation on accessing other documents.
Related
I want the user to only see books with the same userID as its own userID. What do I set rules to? For reference here is my current rules but it allows access to everyoes books once logged in.
service cloud.firestore {
match /databases/{database}/documents {
// Allow only authenticated content owners access
match /booklist/{documents=**} {
allow read, write: if request.auth != null
}
}
}
I want to add the request.auth.uid == userID feature but it is not working when I try to add it.
For reference, here is my collection 'booklist' where you can see the userID field indicated.
Your rules for that would be:
allow read: if request.auth != null && request.auth.uid == resource.data.userID
Combined with this query in your code (because rules are not filters on their own):
db.collection("booklist").where("userID", "==", user.uid).get()
I highly recommend reading the documentation on content-owner only access and securely querying data, specifically securing and querying documents based on a field
I'm writing Firestore security rules for my project. I want to allow users to edit information in their own user page, but not in anyone else's. Right now I don't save userId as a field in each user, only as the reference to the user document. I know how to access fields in each user, but not the reference to them. See picture:
match /Users/{document} {
allow update: if request.auth.uid == userId; //how do I reach the userId without having it as a field
}
I do not want to add userId as a field in each user, there must be an easy way of accessing the path.
As mentioned in the Firestore docs you get the document id from the match query.
In your case this would be document from match /Users/{document}. You could also rename this query to match /Users/{userId} to make it work.
Check the second example in the documentation on using authentication information in security rules:
Another common pattern is to make sure users can only read and write their own data:
service cloud.firestore {
match /databases/{database}/documents {
// Make sure the uid of the requesting user matches name of the user
// document. The wildcard expression {userId} makes the userId variable
// available in rules.
match /users/{userId} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
}
}
}
So in your case that'd be if request.auth.uid == document.
I want to set up certain fields to be private on my user profiles. I have a user documents with name, email, etc but I want to make the gold field read only as I plan to use a cloud function to update this value when a user makes an in app purchase. I've not done in app purchases before so this is the only way I can think of doing it.
I understand I can use wildcard vars in the path when using Firestore security rules, however as far as I'm aware, I can only use wildcard vars in place of the documents and collections.
You are correct that wildards can only be used to identify collections and documents, but not fields. However one option you could have is to create an additional 'private collection' which you could secure with the standard security rules. For example -
users
user1
email
name
gold
user1
goldValue
Then in your security could look something like -
service cloud.firestore {
match /databases/{database}/documents {
match /gold/{userId} {
allow read, update, delete: if request.auth.uid == userId
allow create: if request.auth.uid != null;
}
match /users/{document=**} {
allow read;
allow write: if request.auth.uid != null;
}
}
}
This is a followup to this question
Firestore permissions
I'm trying to set rules on my firestore
service cloud.firestore {
match /databases/{database}/documents {
match /analysis/{analysis} {
allow read, write: if request.auth.uid == resource.data.owner_uid;
}
}
}
My goal is
a. When doing a list operation only those documents belonging to a user are returned
b. only documents a user owns can be read or written by that user.
With the above configuration b. is accomplished.
how do I do accomplish a. ?
Remember that firestore rules are not filters, they're a server-side validation of your queries.
You should always make your queries match your rules, or else you'll get permission errors.
In your case you already made the rule to enforce reading/listing on user owned documents. Now you simply have to make the corresponding query with the right filters :
const userId = firebase.auth().currentUser.uid
db.collection("analysis").where("owner_uid", "==", userId)
Another thing.
With your current rules, your users won't be able to create a new document, only edit an existing one, here are the updated rules to allow that :
allow read: if request.auth.uid == resource.data.owner_uid;
allow write: if request.auth.uid == resource.data.owner_uid
|| request.auth.uid == request.resource.data.owner_uid;
I have a data structure like this (Collections and Documents rather than JSON of course but you get the idea):
{
users: {
user1:{
name: Alice,
groups: {
groupA:{subbed:true},
groupB:{subbed:true}
}
},
user2:{
name: Bob,
groups: {
groupC:{subbed:true},
groupD:{subbed:true}
}
}
}
}
Basically this is registered users IDs and the group IDs that each user is subscribed to. I wanted to write a security rule allowing access to a users profile and sub-collections only if they are the current auth user and, based on my reading of the docs, I thought that a wildcard would achieve this...
match /users/{user=**}{
allow read,write: if user == request.auth.uid;
}
With this in place I can read the user document fine but I get a permissions error when I try and read the groups sub-collection. I can only make it work by matching the sub-collection explicitly...
match /appUsers/{user}{
allow read,write: if user == request.auth.uid;
match /groups/{group}{
allow read,write: if user == request.auth.uid;
}
}
...so my question is, what is the difference between the two examples and what am I misunderstanding about the recursive wildcards? I thought that the {user=**} part of the first example should grant access to the user document and all its sub-collections, sub-sub-collections etc etc ad infinitum (for the authorised user) and should remove the need to write rules specifically for data stored lower down as I have had to do in the second example.
I've only been messing around with Firestore for a short time so this could be a real dumb question :)
Thanks all
The firebase docs are a bit confusing when it comes to using the recursive while card. What I found in testing was that I needed to set two rules to give a user permission to write to the users document and all sub collections (and their sub documents) which is the most logical setup for managing user data.
You must set two rules.
Give user permission to the /users/{userId} document
Give user permission to all sub collections and their sub documents that begin at the /users/{userId} path.
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
match /users/{userId}/{document=**} {
allow read, write: if request.auth.uid == userId;
}
}
}
Rules
Sorry about including the images. I couldn't get SO to format them correctly.
I think the problem is that, while you are indeed using the subcollections wildcard =**, you are then allowing permissions only if user == request.auth.uid, so this is what happens (pseudocode):
(when accessing users/aHt3vGtyggD5fgGHJ)
user = 'aHt3vGtyggD5fgGHJ'
user == request.auth.uid? Yes
allow access
(when accessing users/aHt3vGtyggD5fgGHJ/groups/h1s5GDS53)
user = 'aHt3vGtyggD5fgGHJ/groups/h1s5GDS53'
user == request.auth.uid? No
deny access
You have two options: either you do as you've done and explicitly match the subcollection, or use this:
function checkAuthorization(usr) {
return usr.split('/')[0] == request.auth.uid;
}
match /users/{user=**}{
allow read,write: if checkAuthorization(user);
}
(the function must be inside your match /databases/{database}/documents, like your rule)
Let me know if this works :)
Security rules now has version 2.
match/cities/{city}/{document=**} matches documents in any
subcollections as well as documents in the cities collection.
You must opt-in to version 2 by adding rules_version = '2'; at the top
of your security rules.
Recursive wildcards (version 2).
This is what works for me:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Matches any document in the cities collection as well as any document
// in a subcollection.
match /cities/{city}/{document=**} {
allow read, write: if <condition>;
}
}
}