无需身份验证即可写入/更新特定字段的 Firestore 规则

Ank*_*was 3 firebase firebase-security google-cloud-firestore

我想在不请求身份验证服务的情况下只授予我的 firestore 数据库集合中的一个字段的写入/更新访问权限。我的firestore规则是:

service cloud.firestore {
  match /databases/{database}/documents {
    match /businesses/{businessId} {
      allow read;
      allow write: if request.auth.uid != null;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我的数据库结构businesses是:

addedBy: string;
address: string;
category: string;
claim: boolean;
city: string;
email: string;
id: string;
likes: number;
location: {
    _lat: number,
    _long: number
};
name: string;
ocHours: [{
    day: string,
    from: string,
    status: string,
    to: string
}];
phone: number;
sponsored: boolean;
state: string;
status: string;
verificationCode: string;
Run Code Online (Sandbox Code Playgroud)

我只想更新claim没有request.auth.uid != null.

有什么建议?

小智 9

正如 Ron 所说,firestore 规则中的权限分配只能应用于整个文档。然而,有一种允许写入/更新/删除/创建特定文件的方法,那就是确保传入的更改对象只有您想要授予权限的字段。你这样做:

  1. 读取传入对象中的所有键: request.resource.data.keys()
  2. 确保对象中的唯一键是 hasOnly(["claim"])

service cloud.firestore {
    match /databases/{database}/documents {
        match /businesses/{businessId} {
            allow read;
            allow write: if request.resource.data.keys().hasOnly(["claim"]); 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望它有所帮助,尽管这个问题已经发布了一段时间!!


Mat*_*ati 6

我不知道这个线程是否仍然有效,但是在寻找我偶然发现rules.MapDiff规范的解决方案时,它正是您正在寻找的:

// Compare two Map objects and return whether the key "a" has been
// affected; that is, key "a" was added or removed, or its value was updated.
request.resource.data.diff(resource.data).affectedKeys().hasOnly(["a"]);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此处https://firebase.google.com/docs/reference/rules/rules.MapDiff