There will be a scenario where you will want to partially update a document on the Cloud Firestore without compromising security rules.
Let’s say you have an orders collection and a signed-in user with a user role that can create a new order document in that collection, like in the screenshot below.
Recommended
Firebase Cloud Firestore — Add, Update, Get, Delete, OrderBy, Limit
User Role
The READ and WRITE security rules to access the orders collection for a user would be like this:
WRITE RULE
match /orders/{ordersId} {
allow write: if
request.auth.uid != null && request.auth.token.isUser == true
}
The above security rule will allow a user to create a new document when he/she is logged in and the user role is isUser.
At this stage, you may wonder where the isUser role coming from?
There are a couple of ways to create user roles in Firebase. I use Auth Claims to create roles via Cloud Functions.
For more information on this topic, take a look at my other article that covers in-depth on how to create user roles using Auth Claims.
Recommended
Firebase + Vue.js ← Role Based Authentication & Authorization
READ RULE for a user to access his/her own orders not others.
match /orders/{ordersId} {
allow write: if
request.auth.uid == resource.data.user.uid && request.auth.token.isUser == true
}
The above security rule will allow users to get orders when the logged-in user’s uid matches the uid which is inside the user field in the order document like in the screenshot below.
The security rule also checks if the logged-in user has an isUser role.
That’s pretty straight forward.
Driver Role
As you can see from the order image below, I’ve assigned a driver to the order as soon as it’s created. I did it this way for demonstration purposes.
In the real world, you’ll need to assign a driver after the order is placed via the Admin panel or by sending an order notification to the available drivers to accept the order before the order is placed, then add it to the order document.
When a driver is assigned to the order, he/she needs to access certain information in the order, such as the store name, store address, user address, etc.
So let’s give the READ access to the order that the driver is assigned to.
match /orders/{ordersId} {
allow read: if
request.auth.uid == resource.data.driver.uid && request.auth.token.isDriver == true
}
That’s good.
Now the user can READ and WRITE his/her own order and the driver can only READ the order document.
Nice.
Recommended
Firebase + Vue.js ← Role Based Authentication & Authorization
Order Status
Now, I want to provide the order status to the user as the driver progresses with his/her order, such as food picked, delivered, etc.
Top comments (0)