FireStore规则检查是否正在插入或更新记录

时间:2017-11-28 14:02:35

标签: firebase firebase-security google-cloud-firestore

我在firebase项目上设置了以下firestore规则

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

上面评论的行不起作用

  • 我需要检查资源是否正在插入或更新,resource == null部分无法正常工作
  • created_atupdated_at包含时间戳,is timestamp不起作用

如果有人想知道,resource.data.author包含用户的uid

2 个答案:

答案 0 :(得分:0)

the documentation开始,写入可以细分为:

  • 创建
  • 更新
  • 删除

所以,在这种情况下,你会想要这样的东西:

service cloud.firestore {
  match /databases/{database}/documents {
    match /news/{news} {
      //read rules here...
      allow create: if true; 
      allow update: if true; 
      allow delete: if true; 
    }
  }
  //other rules here...
}

还有good documentation for validating timestamps。我强烈建议尽可能使用firebase.firestore.FieldValue.serverTimestamp()

答案 1 :(得分:0)

我在文档中寻找相同的细节,以下对我使用时间戳有效,如果我尝试发送一个字符串失败(其中“lastUpdated”应该与你的日期属性交换)

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