FireStore Rules check if record is being inserted or updated

Viewed 611

I set the following firestore rule on my firebase project

service cloud.firestore {
    match /databases/{database}/documents {
        match /news/{news} {
            allow read: if true;
            allow write: if request.auth != null
                         // && (
                               // (resource == null && request.resource.data.author == request.auth.uid) || 
                               // request.auth.uid == resource.data.author == request.resource.data.author || 
                               // get(/users/$(request.auth.uid)).role in ["editor", "admin"]
                            // )
                         && request.resource.data.keys().hasAll(['title', 'body', 'images', 'tags', 'source', 'web_link', 'created_at', 'updated_at', 'author'])
                         && request.resource.data.title is string && request.resource.data.title.size() >= 10 && request.resource.data.title.size() <= 100
                         && request.resource.data.body is string && request.resource.data.body.size() >= 300 && request.resource.data.body.size() <= 500
                         && request.resource.data.images is list && request.resource.data.images.size() >= 0
                         && request.resource.data.tags is list && request.resource.data.tags.size() >= 0
                         && request.resource.data.source is string && request.resource.data.source.size() > 0 && request.resource.data.title.size() <= 100
                         && request.resource.data.web_link is string && request.resource.data.web_link.size() > 0
                         // && request.resource.data.created_at is timestamp
                         // && request.resource.data.updated_at is timestamp
                         ;
        }
        match /users/{userId} {
            allow read, write: if request.auth.uid == userId || get(/users/$(request.auth.uid)).role == "admin"
        }
        match /{document=**} {
            allow read, write: if false;
        }
    }
}

The lines commented above don't work

  • I need to check if the resource is being inserted or updated, the resource == null part doesn't work
  • created_at and updated_at contain timestamp, and is timestamp doesn't work

In case anyone is wondering, resource.data.author contains uid of a user

2 Answers

I was looking for the same details in the documentation, the following works for me using timestamps and fails if I try send a string (where "lastUpdated" should be swapped with whatever your date property is)

request.resource.data.lastUpdated.date() is timestamp
Related