Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase Security Rule fails even though the request would be correct

I’ve programmed a web app with TypeScript and I have a problem with Firebase Firestore. I run the following request and it’s disallowed due to a Firestore Security Rule:

export async function setNewAppointment(appointment: Appointment) {
  const user = auth.currentUser;

  await addDoc(collection(db, "appointments"), {
    user_id: "blah",
    id: appointment.id,
    title: appointment.title,
    start_time: Timestamp.fromMillis(appointment.start_time),
    end_time: Timestamp.fromMillis(appointment.end_time),
    description: appointment.description,
    location: appointment.location,
  });
}

This is my Firebase Security Rule:

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        match /{document=**} {
            allow read, write: if false;
        }
        match /users/{userId} {
            allow read, write: if request.auth.uid == userId;
        }
        match /appointments/{appointmentId} {
            allow read, write: if "blah" == resource.data.user_id;
        }
    }
}

My Error message: "Uncaught (in promise) FirebaseError: Missing or insufficient permissions."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The resource.data is an object containing existing data in the document but as you are trying to create a new document, resource is null. Try using request.resource instead that contains the the data that’ll be present if operation succeeds:

match /appointments/{appointmentId} {
  allow read: if <rule>;
  allow write: if "blah" == request.resource.data.user_id;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading