Reputation: 1
I am building an ecommerce android app with Firebase how can I isolate different users like Customer and Seller in Firebase Authentication and give access to read and write to their respective database nodes in Firebase Database(Realtime Database)
Upvotes: 0
Views: 107
Reputation: 26256
This can be achieved using a database structure similar to this:
{
"users": {
"someUserId-782nafdca9": {
"name": "Joe Smith",
"type": "customer",
...
},
"someUserId-78sdfgs523": {
"name": "Example Supplier Co.",
"type": "seller",
...
}
},
"dataForSellers": {
...
},
"dataForCustomers": {
...
}
}
with the following rules:
"rules": {
"users": {
"$uid": {
".read": "auth.uid == $uid",
".write": "auth.uid == $uid",
}
},
"dataForCustomers": {
".read": "auth != null && root.child('users').child(auth.uid).child('type').val() == 'customer'",
".write": "auth != null && root.child('users').child(auth.uid).child('type').val() == 'customer'"
},
"dataForSellers": {
".read": "auth != null && root.child('users').child(auth.uid).child('type').val() == 'seller'",
".write": "auth != null && root.child('users').child(auth.uid).child('type').val() == 'seller'"
}
}
Security rules have a number of predefined variables that can be used to check various conditions. The rules above make use of the auth
and root
variables.
The rules for user data under users/$userId
, currently only check to see if the current user matches the user data they are trying to modify (auth.uid == $uid
).
The rules for dataForCustomers
and dataForSellers
first check if the user is logged in (auth != null
) and then check that their user data (accessed by root.child('users').child(auth.uid)
) contains the correct value for type
.
Note 1: As @Doug mentioned in their comment, the documentation for security rules can be found here with further specifics on securing user data.
Note 2: Like the official documentation, this example is not without flaws. For example, at any time with the security rules as above, if a user is logged in, they can:
Note 3: Don't just nest all your data under "dataForSellers" and "dataForCustomers", these were given as placeholder names for your own data trees such as "products", "shipping", "orders", etc.
Note 4: As you are just beginning with the RTDB, make sure to have a look at the RTDB vs. Firestore article. For ecommerce, you might be better off using Firestore instead just for it's filtering alone.
Upvotes: 1