Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase - Get current user id [duplicate]

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)

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.

Thanks...

like image 544
nick clarke Avatar asked Aug 10 '17 12:08

nick clarke


Video Answer


1 Answers

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.

Then in your cloud function you can use: https://firebase.google.com/docs/auth/admin/verify-id-tokens

Example:

admin.auth().verifyIdToken(idToken)   .then(function(decodedToken) {     var uid = decodedToken.uid;     // ...   }).catch(function(error) {     // Handle error   }); 

The documentation for decodedToken is here: https://firebase.google.com/docs/reference/admin/node/admin.auth.DecodedIdToken#uid

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

Which returns a UserRecord https://firebase.google.com/docs/reference/admin/node/admin.auth.UserRecord

like image 146
Kim Avatar answered Oct 01 '22 08:10

Kim