If I have a collection in firebase with several documents inside and each document has a field called for example "role", is it possible to show a user only the documents that belong to him when the whole collection is fetched?
CodePudding user response:
Yes. You can do this.
Let's assume the user has the role 'student', you can fetch all documents .where('role', isEqualTo: 'student')
.
NB: role could also be the userId (and you can fetch all documents where role is userId).
You can use the following firebase rules to prevent unauthorised access.
match /document/{docs=**} {
allow write, read: if isAllowed();
}
function isAllowed() {
// request.resource.data is the data being fetched.
return request.resource.data.role == 'student';
}
function userRole() {
// returns the user role. Use this if the user role is stored in a document.
return get(/databases/$(database)/documents/users/$(userId)).data.role;
}
NB: your query must contain .where('role', isEqualTo: 'student')
if not it will fail with insufficient permissions.