【问题标题】:Firestore rule not working as expectedFirestore 规则未按预期工作
【发布时间】:2018-08-12 04:44:46
【问题描述】:

我在 Firestore 上设置了以下规则。

service cloud.firestore {
  match /databases/{database}/documents {
    match /items/{itemid} {
        allow read, write: if request.auth.uid == resource.data.owner;
    }
  }
}

在我的 Angular 服务中,我正在初始化集合,如下所示:

constructor(private authService: AuthService, private fs: AngularFirestore) {
  this.itemsCollection = this.fs.collection('items', cr => {
    return cr.where('owner', '==', authService.currentUserId);
  });
}

读取项的代码:

items() {
  return this.itemsCollection.valueChanges();
}

写入项的代码:

addItem(item: ItemEntry): Observable<DocumentReference> {
  item.owner = this.authService.currentUserId;
  return Observable.fromPromise(this.itemsCollection.add(item));
}

read 操作正常工作,但 write 操作 (addItem) 失败并出现错误

权限缺失或不足。

想不通,为什么?

【问题讨论】:

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


    【解决方案1】:

    那是因为resource 变量:

    包含存储在文档中的字段和值的映射 resource.data.

    这意味着resource.data 仅包含已存储在数据库中的数据。

    您应该改用request.resource。因为它包含正在写入数据库的数据。您的新规则如下所示:

    allow read, write: if request.auth.uid == request.resource.data.owner;
    

    【讨论】:

    • 在更新时,您应该检查现有数据,而不是新数据。所以只需在写入规则中添加“或不存在”即可。
    • 非常感谢,像魅力一样工作。不过,不得不拆分规则。读取的原始规则,写入的新规则。谢谢阿甘。
    猜你喜欢
    • 2020-10-30
    • 1970-01-01
    • 2013-07-24
    • 2013-08-11
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2020-01-12
    相关资源
    最近更新 更多