Search code examples
firebasegoogle-cloud-firestoregoogle-cloud-functions

How to get the authenticated user with uid through onDocumentCreatedWithAuthContext


All Firebase users in my app has a document in the Profile collection.

All my profile document ids are equal to user.uid when I created them in Flutter like this. Within the profile document, there will be public data regarding the user such as followers, followings, likedSubmissions and etc.

            final DocumentReference<Profile> reference =
                Profile.collection.doc(**user.uid**);
            await reference.set(
              Profile(
                username: _username!,
                uid: user.uid,
                reference: reference,
              ),
            );

How do I get the user's Profile in onDocumentCreatedWithAuthoContext? I am assuming that I can just get the uid of the authorized user and use it in my path.

exports.onSubmissionLikeDocumentCreated = onDocumentCreatedWithAuthContext(
    "submission/{submissionId}/like/{likeId}",
    (event) => {
      const batch = db.batch();
      const submissionReference =
          db.doc(`submission/${event.params.submissionId}`);
      batch.update(
          submissionReference,
          {
            likesCount: FieldValue.increment(1),
          },
      );
      batch.update(
          **How to get uid here?**
          const uid = ?????????????
          db.doc(`profile/${uid}`),
          {
            likedSubmissionReferences:
                FieldValue.arrayUnion(submissionReference),
          },
      );
      const reference =
          event.data.ref;
      batch.set(
          reference,
          {
            reference,
            createdAt: FieldValue.serverTimestamp(),
          },
          {
            merge: true,
          },
      );
      return batch.commit();
    },
);

Solution

  • As mentioned by @Doug Stevenson, The documentation suggests that you need to look inside an event to find user data: const { authType, authId } = event.

    Here AuthId stands for a unique identifier of the principal that triggered the occurrence. This might, for example, be a unique ID in an identity database (userID), an email of a platform user or service account, or the label for an API key.

    You can check this thread for reference.