I’m getting a “permission-denied” error when trying to update a document in Firestore. I’ve ensured that my Firestore rules allow the operation, but the update still fails.
Here are the relevant Firestore rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Check if the user is an admin
function isAdmin() {
return request.auth != null &&
get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 0;
}
// Check if the user is a business person
function isBusinessPerson() {
return request.auth != null &&
get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1;
}
// Rules for the clients collection
match /clients/{clientId} {
allow update: if isAdmin() || isBusinessPerson();
}
}
}
Here are the constants I use in the code:
const keyClient = 'clients';
const keyAddress = 'addresses';
const keyPhone = 'phone';
const keyName = 'name';
Here is the relevant update code:
Future<DataResult<ClientModel>> update(ClientModel client) async {
try {
if (client.id == null) {
throw Exception('Client ID cannot be null for update operation.');
}
await _firebase.collection(keyClient).doc(client.id).update(client.toMap());
return DataResult.success(client);
} catch (err) {
final message = 'ClientFirebaseRepository.update: $err';
log(message);
return DataResult.failure(FireStoreFailure(message: message));
}
}
I’ve verified the following:
- The create operation works as expected and follows the rules.
- The
allow update: if true;
rule also doesn’t work. - I’ve logged
locator<UserStore>().currentUser!
andFirebaseAuth.instance.currentUser
and they match. - Here is a sample of my log output for an admin user:
[log] admin: 0 [log] ClientFirebaseRepository.update: [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.
I’m not sure what’s causing the update to fail. Any suggestions or insights would be greatly appreciated!
What I’ve tried:
- Ensured that
allow update: if true;
is applied to see if it was a rule logic issue, but the update still fails. - Checked that create operations work fine, and removing permissions for create does indeed block the operation, so the rules are applied.
- Verified that the user has an admin role (as shown in the log).
- Logged both the
UID
fromlocator<UserStore>().currentUser!
andFirebaseAuth.instance.currentUser
. Both values match, so they are not out of sync.
Why am I getting a “permission denied” error when trying to update documents, even when the rules seem correct and allow updates? Is there something I’m missing with Firestore security rules or the way the update operation is performed in the code?
I was expecting that the update operation would work since the rules should allow the update for users with the admin role or business role.
4