Wednesday 27 July 2022

Firebase security rules checks for the incoming request and database collection email

I'm creating a Flutter Todo app that allow users to add a task for himself or he could send it to another user via their account email.

My Firebase database have the following fields: title, isChecked, recipient, sender, senderUID enter image description here

My current Firebase security rules are as following

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {

 function isOwnerOrAdmin(reminder, auth) {
  let isOwner = auth.token.email == reminder.recipient;
  let isAdmin = auth.token.isAdmin == true;
  return isOwner || isAdmin;
 }

 match /reminders/{reminder} {
  allow create: if
        // User is author
        request.auth.uid == request.resource.data.senderUID;
  
  allow update: 
        // User is recipient or admin
        if isOwnerOrAdmin(resource.data, request.auth) &&
        // only 'title' and 'isChecked' could be modified
        request.resource.data.diff(resource.data).unchangedKeys().hasAll([
          "recipient",
          "sender",
          "senderUID"
          ]);
          
  // Can be read or deleted by recipent or admin
  allow read, delete: if isOwnerOrAdmin(resource.data, request.auth);
  }

In my code, I'm using the following code to make updates to a task,

var collection = _firestore.collection('reminders');
var snapshot = await collection.where('title', isEqualTo: task.title).where('recipient', isEqualTo: loggedInUser.email.toString()).get();
await snapshot.docs.first.reference.update({'isChecked': task.isChecked});

Similarly, the following code is used to delete a task

var collection = _firestore.collection('reminders');
var snapshot = await collection.where('title', isEqualTo: task.title).where('recipient', isEqualTo: loggedInUser.email.toString()).get();
await snapshot.docs.first.reference.delete();

Update and Delete do not work with my new set of rules with the INSUFFICIENT PERMISSION in the output, what did I do wrong? I could only create new doccument, but can't update or delete it (via code).



from Firebase security rules checks for the incoming request and database collection email

No comments:

Post a Comment