admin.auth().currentUser; returning undefined in Cloud Function

淺唱寂寞╮ 提交于 2021-02-08 11:15:57

问题


I am trying to create a function that, when a device is registered in the app, will attach this device uid to the uid of the signed-in user who registered the device (this is in another firestore collection that is automatically created when a user registers).

Here is my code:

exports.addDeviceToUser = functions.firestore.document('device-names/{device}').onUpdate((change, context) => {
    const currentUser = admin.auth().currentUser;
    const deviceName = context.params.device;
    var usersRef = db.collection('users');
    var queryRef = usersRef.where('uid', '==', currentUser.uid);

    if (authVar.exists) {
        return queryRef.update({sensors: deviceName}).then((writeResult => {
        return console.log('Device attached');
        }));
    } else {return console.log('Device attachment failed, user not signed in');}
});

I am consistently getting this error: "TypeError: Cannot read property 'uid' of undefined." Obviously I am not able to access the auth information of the current user. Why?


回答1:


The Admin SDK doesn't have a sense of current user. When you say admin.auth(), you're getting back an Auth object. As you can see from the API docs, there is no currentUser property on it. Only the Firebase client SDK has a sense of current user, because you use that to get the user logged in.

If you need the client app to tell Cloud Functions code work with the user's identity, you have to send it an ID token from the client, and verify it on the server. Then the server can know who the end user is, and perform actions on their behalf. Typically you do this with an HTTP type trigger. Callable functions transmit this data automatically between the client and server, but you can do it manually yourself using code that works like this sample.

Right now, Firestore triggers don't have immediate access to the end user that made a change in the database. However, if you use the Auth UID of the user as the key of the document, and protect that document with security rules, you can at least infer the UID of the user based on the changes they make to the document by pulling it out of the id of the document that changed.




回答2:


Because, by design, Cloud Functions executes on the back end and do not hold any information on which user was authenticated when adding/modifying the data in the database.

When writing the data in the 'device-names/{device}' document (from your app), you could include an extra piece of data which is the uid of the current user.



来源:https://stackoverflow.com/questions/50235846/admin-auth-currentuser-returning-undefined-in-cloud-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!