我只是想使用Firebase函数获取经过身份验证的用户的“ uid ”。但是每次我在“ firebase functions:shell ”中运行该函数时。我得到这些错误。谁能帮我解决这个问题?
“ context.auth.uid” 类型错误:无法读取未定义的属性'uid'
exports.sendNewUser = functions.database.ref('/Users/')
.onCreate(async (snapshot, context) => {
const userId = await context.auth.uid;
const tokenPath = await admin.database().ref('Notify').once('value')
var message = []
tokenPath.forEach((childSnapshot) => {
var allTokens = childSnapshot.val().expo
if (allTokens) {
message.push({
"to": allTokens,
"header": " Users",
"body": "New user has been added, check them out!!!"
})
}
})
await fetch('https://exp.host/--/api/v2/push/send', {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(message)
})
console.log("The user ID is : " + userId)
})
Package.json:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"dateformat": "^3.0.3",
"firebase-admin": "6.3.0",
"firebase-functions": "^2.1.0",
"node-fetch": "^2.3.0"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0"
},
"private": true
}
答案 0 :(得分:0)
running Realtime Database triggers的文档很明确:
默认情况下,shell运行带有以下内容的实时数据库功能 管理特权。使用auth选项代替运行 可以作为特定的最终用户或未经身份验证的用户使用
# to mock unauthenticated user myDatabaseFunction('data', {authMode: 'USER'}) # to mock end user myDatabaseFunction('data', {auth: {uid: 'abcd'}})
您需要在上下文中传递模拟auth有效负载的最后一个对象。否则,auth将不包含任何内容。
发布后它将正常工作。
访问uid时不需要使用await
。这不是一个异步函数。
答案 1 :(得分:0)
context.auth.uid将由onCreate触发器定义,因为它是由云功能运行时而不是由创建文档的用户触发的。