在客户端
您可以为此use custom File Metadata。它的作用是将Map<String, String> 添加到文件的元数据中。并且由于 Map 中的键是唯一的,您可以将用户 B 的 id 存储为键并使用空字符串作为值:
StorageMetadata metadata = new StorageMetadata.Builder()
.setCustomMetadata(userId,"") //User B's id
.build();
然后使用updateMetadata()方法分享文件:
picture1Ref.updateMetadata(metadata)
.addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
@Override
public void onSuccess(StorageMetadata storageMetadata) {
// Updated metadata is in storageMetadata
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Uh-oh, an error occurred!
}
});
在 Firebase 控制台上
然后为了在 Firebase 端验证这一点,您可以设置如下规则:
service firebase.storage {
match /b/{bucket}/o {
match /images/{userId}/{pictureName}{
allow write: if request.auth.uid == userId;
allow read: if request.auth.uid == userId || request.auth.uid in resource.metadata.keys();
}
}
}
与更多用户分享
如果您想与更多用户(比如用户 C 和 D)共享同一个文件,您可以重复相同的步骤,将他们的 id 传递给自定义元数据,因为只有元数据中指定的属性会被更新,而所有其他的保持不变。
撤销用户访问权限
如果您想撤销特定用户的访问权限,您可以将自定义元数据设置为空值并再次调用updateMetadata()。
StorageMetadata metadata = new StorageMetadata.Builder()
.setCustomMetadata(userId, null)
.build();