Search code examples
typescriptfirebasegoogle-cloud-firestorefirebase-security

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."


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;
    }