我们能否使用Firestore数据来授予或限制访问在Firebase Cloud Storage上托管的文件?
我想要用作Firebase安全规则的示例
allow write: if get(/databases/mydbname/documents/guilds/$(guildID)).data.users[(request.auth.uid)] in ["Admin", "Member"];
我们能否使用Firestore数据来授予或限制访问在Firebase Cloud Storage上托管的文件?
我想要用作Firebase安全规则的示例
allow write: if get(/databases/mydbname/documents/guilds/$(guildID)).data.users[(request.auth.uid)] in ["Admin", "Member"];
更新(2022年10月):现在可以使用新的firestore.get()
和firestore.exists()
函数从 Cloud Storage 安全规则内访问 Cloud Firestore 了。请参阅博客文章“Announcing cross-service Security Rules”和“使用 Cloud Firestore 增强 Cloud Storage 安全规则”的文档。
以下是以前的答案,供参考:
目前没有办法从另一个产品的安全规则内访问不同的 Firebase 产品。请参见:is there a way to authenticate user role in firebase storage rules?
但似乎你正在尝试检查用户的组成员身份。我建议你将其建模为所谓的自定义声明。而不是在数据库中查找组成员资格,您可以通过使用 Firebase Admin SDK 将声明“用户 {uid} 是 {guild1} 组的成员”写入用户配置文件中(或者除此之外):“通过管理 SDK 设置和验证自定义用户声明”。
admin.auth().setCustomUserClaims(uid, {guild1: true}).then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
});
完成这一步后,您可以在安全规则中检查公会成员身份:
allow read: if request.auth.token.guild1 == true;
我不确定如何将公会成员资格建模为地图,如果这种情况发生,我会更新这个答案。
get()
和exist()
函数之前使用firestore.
前缀,如下所示:allow write: if firestore.get(/databases/(default)/documents/col/docId/).data.field == "value";
(default)
。这不是Firestore规则中的通配符,因此不是$(database)
。 const storageRef = ref(
storage,
`files/${fileName}`,
);
const uploadTask = uploadBytesResumable(storageRef, file, {
customMetadata: {
uploaderId: userId,
},
});
match /files/{fileName} {
allow create: if request.auth != null &&
request.resource.metadata.uploaderId == request.auth.uid
}
export const onFinalize = functions
.storage.object()
.onFinalize(async object => {
// We can trust object.metadata.uploaderId, so check Firestore if user is able to upload file
if (!(await canUploadFile(object.metadata.uploaderId, object.name))) {
await storage.bucket(object.bucket).file(object.name).delete();
throw new Error(
`Permission error: ${object.metadata.uploaderId} not allowed to upload ${object.name}`,
);
}
// Continue
});