3

I want to define custom functions on Firebase using firebase-tools. Is there a way to get userId from firebase-functions?

Say on this code sample, is it possible to get the user who sent the request?

const functions = require('firebase-functions');

    exports.helloWorld = functions.https.onRequest((request, response) => {
     response.send("Hello from Firebase!");
    });

I have tried getting it with the following code unsuccessfully functions.auth.user().uid.

I am quite new to both js and firebase, so go easy on me please, I am trying to learn.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
GIV
  • 405
  • 3
  • 9
  • 16

2 Answers2

6

You're over-simplifying the way HTTP triggers work. They have no knowledge of anything about the entity on the end making the request. It could be a user, or just some automated program. The user doesn't have to be authenticated in order to access your function.

If you want to limit access to your HTTP trigger to only authenticated users, you could try something as described in this other question. There is official sample code that shows what you need to do.

Bottom line is this. Unless you do something to safely transmit to the function who the user is (identified by an id token), then you really have no idea who they are.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

Think I find a better answer from this post : https://medium.com/super-declarative/dev-snack-testing-firebase-cloud-functions-with-user-id-tokens-83841d3f06c. Basically 2 ways for http functions

  1. functions.https.onRequest : You may get, if available, the token from the request and then use firebase admin api to get user UID;
  2. functions.https.onCall for authenticated request : You get it from exposed context object
Breton F.
  • 177
  • 1
  • 6