Sebastian Marambio
Sebastian Marambio

Reputation: 21

How can I retrieve the authentication data of a user when using a Firebase callable function?

My mobile app built in Flutter uses google login to register users. From within this app I am calling a Firebase cloud function (called questionAnswer) using the Cloud Functions Plugin for Flutter.

If I understand correctly from this documentation, the https request should automatically include the Firebase authentication of the user.

How can I retrieve the authentication information of the user from within the Cloud Function? I need it in order to access data associated with that specific user in a Firebase Cloud Database. Should I include the google auth token as a parameter in the https request?

Here is my code in the Flutter app:

final HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(
      functionName: 'questionAnswer',
  );

 fetchHttps() async {
   dynamic resp = await callable.call();
   print(resp);
 }

This is the code in the Cloud Function

exports.questionAnswer = functions.https.onCall(() => {
  console.log('addNumbersLog', "holaLog");
    return answer;
  });

Upvotes: 1

Views: 1102

Answers (2)

Diego Zacarias
Diego Zacarias

Reputation: 793

You can obtain the uid of the user from the CallableContext parameter, which is passed to your onCall handler as the second argument.

From there on you can retrieve the Firebase UserRecord using the .getUser() method and passing in the uid.

exports.questionAnswer = functions.https.onCall((data, { auth }) => {
    admin.auth().getUser(auth.uid)
      .then((userRecord) => {
        // See the UserRecord reference doc for the contents of userRecord.
        console.log('Successfully fetched user data:', userRecord.toJSON());
      })
      .catch(function(error) {
        console.log('Error fetching user data:', error);
      });
  });
});

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317467

As you can see from the documentation, auth information is in the second parameter passed to the function. You will need to declare and use it:

exports.questionAnswer = functions.https.onCall((data, context) => {
  console.log('addNumbersLog', "holaLog");
  console.log(context.auth);
  return answer;
});

context here is a CallableContext object.

Upvotes: 1

Related Questions