Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Cloud Firestore trigger context.auth is always null [duplicate]

I am using Firebase and Cloud Firestore to build a group app, where users should be able to create groups and add members to it.

As a user creates a group, I want a cloud trigger to add that user to the group's member list after the group has been created. The trigger looks like this:

exports.addCreatorAsAdmin = firestore
  .document('groups/{group}')
  .onCreate((snap, context) => {
    if (context.auth == null) { return unauthorizedError() }
    const path = `groups/${context.params.group}/members/${context.auth.uid}`;
    return db.doc(path).create({});
  });

As I run the app, sign in the user and create a team, the function is correctly triggered. However, I always hit the unauthorized error, which means that context.auth is null.

TLDR; the user is correctly signed in, but the trigger is unauthorized. Can anyone help me out?

like image 937
Daniel Saidi Avatar asked Oct 22 '19 06:10

Daniel Saidi


1 Answers

Cloud Firestore currently doesn't support context.auth for determining which user made the change. As you can see from the API documentation:

This field is only populated for Realtime Database triggers and Callable functions. For an unauthenticated user, this field is null. For Firebase admin users and event types that do not provide user information, this field does not exist.

What you can do instead is have the user write their UID into a field of the document, and validate that with security rules as described in this post.

like image 153
Doug Stevenson Avatar answered Nov 04 '22 17:11

Doug Stevenson