Firebase Cloud Functions-如何获取上传文件的用户? [英] Firebase Cloud Functions - How to get user that uploads a file?
问题描述
我有一个管理网站,可将文件上传到Firebase Storage中的特定文件夹.
I have an admin web site that uploads files to a specific folder in Firebase Storage.
从存储云功能中,我需要从上传文件的用户获取经过身份验证的userId.我需要这样做是因为,当用户上传文件时,云功能会启动,执行一些处理并将信息保存在实时数据库中,在该数据库中,我需要保存负责上传操作的用户.
From a Storage cloud functions, I need to get the authenticated userId from the user that uploads the file. I need this because, when the user uploads the file, the cloud function starts, do some process, and save information in the realtime-database, where I need to save the responsible user of the upload action.
我看到从实时数据库云功能获取用户很简单(使用context.auth.uid),但是我没有找到任何类似的存储云功能解决方案.
I saw that get user from a realtime-database cloud function is simple (using context.auth.uid), but I did not find any similar solution to storage cloud functions.
有可能吗?
Tks.
推荐答案
您可以将自定义元数据作为包含String属性的对象上传:
You can upload custom metadata as an object containing String properties:
从文档此处:
var metadata = {
customMetadata: {
'location': 'Yosemite, CA, USA',
'activity': 'Hiking'
}
}
然后,您可以在文件上使用getMetadata
(文档此处)以获取其信息,例如像下面的触发函数中那样获取customMetadata
.
Then you can use getMetadata
on the file (the doc here) to retrieve its information or for example get customMetadata
like in my trigger function below.
例如,在我的iOS应用程序中,我创建了StorageMetadata
并将customMetadata
设置为["user":"userID_AZERRRRR"]
For example and from my iOS application, I created a StorageMetadata
and I set the customMetadata
to ["user":"userID_AZERRRRR"]
在我的node js函数中,我开发了触发函数,如下所示:
In my node js functions, I developed the trigger function like this:
exports.testStorageOnFinalize = functions.storage.object().onFinalize(uploadedObject => {
console.log('metadata keys', Object.keys(uploadedObject.metadata));
console.log('metadata user', uploadedObject.metadata['user']);
})
在我的日志控制台中:
3:00:20.140 PM信息testStorageOnFinalize 元数据用户userID_AZERRRRR
风险
根据道格的评论,此解决方案并不完全安全,因为元数据可能会被伪造.
From Doug comment, this solution is not fully secure because the meta data could be faked.
因此,要解决此问题,我们可以使用安全性规则进行存储,以检查用户是否等于已标识的用户:
So, to resolve this, we can use the security rules for storage in order to check if the user is equal to identified user:
// Allow reads if a certain metadata field matches a desired value
allow read: if resource.metadata.user == request.auth.uid;
您可以在此处
这篇关于Firebase Cloud Functions-如何获取上传文件的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!