0

I use anonymous user in my app and have a function that create user with only uid

export const createUserObject = functions.auth.user().onCreate((user, context) => {
  const userData = {"uid": user.uid}
  admin.firestore().collection("users").doc(user.uid).set(userData).then(writeResult => {
    console.log('User Created result:', writeResult);
  }).catch(err => {
    console.log(err);
  });
});

Now I want to add another endpoint for user to create note. I plan to make note it own collection with 2 fields content and uid to reference back to user who create it.

Is there a way for Firebase function to retrieve uid for a triggered user? So I can write something like this, or I have to make user send it along with note?

export const addNote = functions.https.onRequest((request, response) => {

  if(request.method !== "POST"){
    response.sendStatus(404)
    return;
  }
  const content = request.body.content

  const data = {
    content: content,
    uid: HOW_CAN_I_GET_CURRENT_USER
  };

  let db = admin.firestore()

  return db.collection("notes").add({content: content}).then((ref) => {
     response.sendStatus(201)
  })
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
sarunw
  • 8,036
  • 11
  • 48
  • 84
  • The user that triggered the HTTP function is available through `req.headers.authorization`. See this answer for a link to a sample: https://stackoverflow.com/questions/42751074/how-to-protect-firebase-cloud-function-http-endpoint-to-allow-only-firebase-auth – Frank van Puffelen May 20 '18 at 15:46
  • 1
    You don't really need a cloud function for that. Firebase encourages manipulating data directly from the client, without the need for backend code. So you could create the notes the same way you create the user document. – Ricardo Smania May 20 '18 at 16:25
  • @RicardoSmania so I create note and put uid on client side? Clients mange the relation themselves? – sarunw May 21 '18 at 04:53
  • @sarunw yes, since you are already authenticating the user you can use the uid from the client. You should probably also define security rules so that users only see and change data they own. – Ricardo Smania May 22 '18 at 10:58
  • @FrankvanPuffelen Could you post your solution as an answer, please? – Rubén C. Jul 12 '18 at 14:44

1 Answers1

0

The user that triggered the HTTP function is available through req.headers.authorization.

See this answer for a link to a sample, and another option using Callable HTTPS functions: How to protect firebase Cloud Function HTTP endpoint to allow only Firebase authenticated users?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807