skip to Main Content

I’m using a google cloud function to handle firestore data deletion like so:

exports.deleteAccount = https.onCall(
    async (data, auth) => {
        const uid = data.auth.uid;
        // ...
       
    }
);

My firestore database is structured so that user documents id’s are the user’s uids. Is it safe to use the uid provided in data.auth.uid to handle the deletion? I.e can a different or not authed user provide a different uid?

The function is called in a flutter app like so:

HttpsCallable callable =
        FirebaseFunctions.instanceFor(region: 'asia-southeast1')
            .httpsCallable('deleteAccount');
    await callable();
``

2

Answers


  1. Chosen as BEST ANSWER

    I was referring to first gen documentation:

    // Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
    exports.addMessage = functions.https.onCall((data, context) => {
      // ...
    });
    

    But the function used was a second gen cloud function. Based on the documentation it should be used like this:

    exports.addmessage = onCall((request) => {
      const uid = request.auth.uid;
      // ...
    });
    

    So when using the second generation cloud function, it is ok to use data.auth.uid (written as request.auth.uid in the documentation)


  2. Is it safe to use data.auth.uid?

    Short answer:

    Yes, but there is an error in your code.

    You should use auth.auth.uid instead of data.auth.uid because you do https.onCall(async (data, auth) => {...});. I suggest to use the name context for the second variable passed to the callback instead of auth, as shown in the examples in the doc for 1st gen Callable Cloud Functions.

    Longer answer:

    "With Callable Cloud Functions, Firebase Authentication tokens, FCM tokens, and App Check tokens, when available, are automatically included in requests", as explained in the doc.

    So you can be sure that context.auth.uid returns the uid of the user who calls the Cloud Function (if the user is authenticated in your Flutter app, of course).

    If a user calls the Cloud Function while not being authenticated you can send back an error as shown below, which will stop the Cloud Function execution.

    exports.deleteAccount = https.onCall(
        async (data, context) => {
    
            if (!context.auth) {
             // Throwing an HttpsError so that the client gets the error details.
             throw new functions.https.HttpsError(
               "failed-precondition",
               "The function must be called while authenticated."
             );
            }
    
            const uid = context.auth.uid;
            // ...
           
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search