Firebase的Cloud Functions-获取当前用户ID [英] Cloud Functions for Firebase - Get current user id
问题描述
花了一些时间寻找似乎是一个简单问题的解决方案,但是...如何在云函数内部获取当前用户的详细信息(不使用functions.auth触发器时)?我敢肯定对此必须有一个简单的解决方案. (我希望)
Spent a while searching out a solution to what seems a simple problem but... How can I get the current users details inside a cloud function (when not using an functions.auth trigger)? I'm sure there must be a simple solution to this. (I hope)
感谢您的回复...刚刚完成了,但是如何在存储触发的事件中从Firebase数据库中获取/user/uid?例如
Thanks for the replies... Just done that but how would I get the /user/uid from the Firebase DB within a storage triggered event? e.g.
exports.addUploadInfoToDatabase = functions.storage.object().onChange(event => {
console.log("firebase storage has been changed");
// need to find the uid in here somehow
admin.database().ref(`/user/uid`).push({testKey:"testData"});
})
如果我错过了您的答复,请致谢.
Applogies if I've missed the point in your replies.
谢谢...
推荐答案
首先,您可以通过在用户上调用getIdToken()
来获取当前登录的用户tokenId:
First you can get the current signed-in user tokenId by calling getIdToken()
on the User: https://firebase.google.com/docs/reference/js/firebase.User#getIdToken
firebase.auth().currentUser.getIdToken(true)
.then(function (token) {
// You got the user token
})
.catch(function (err) {
console.error(err);
});
然后将其发送到您的云功能.
Then send it to your cloud function.
然后在您的云功能中可以使用: https://firebase .google.com/docs/auth/admin/verify-id-tokens
Then in your cloud function you can use: https://firebase.google.com/docs/auth/admin/verify-id-tokens
示例:
admin.auth().verifyIdToken(idToken)
.then(function(decodedToken) {
var uid = decodedToken.uid;
// ...
}).catch(function(error) {
// Handle error
});
decodedToken的文档位于此处: https://firebase.google.com/docs/reference/admin/node/admin.auth.DecodedIdToken#uid
The documentation for decodedToken is here: https://firebase.google.com/docs/reference/admin/node/admin.auth.DecodedIdToken#uid
DecodedIdToken包含用户uid,然后您可以通过调用以下命令来获取用户: https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#getUser
DecodedIdToken contains the user uid, then you can get the user by calling this: https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#getUser
哪个返回UserRecord https://firebase.google. com/docs/reference/admin/node/admin.auth.UserRecord
Which returns a UserRecord https://firebase.google.com/docs/reference/admin/node/admin.auth.UserRecord
这篇关于Firebase的Cloud Functions-获取当前用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!