Remove user from firebase with Admin SDK

I need help understanding how to remove a user from my admin panel using the Firebase Admin SDK. When attempting to delete a user, I encountered this error:

Uncaught (in promise) ReferenceError: uid is not defined at eval (ManageCustomer.vue?b113:262)

What might I be doing incorrectly in my code?

Below is the code snippet from index.js that resides in functions folder:

 const functions = require("firebase-functions");
        const admin = require("firebase-admin");
        admin.initializeApp();
        const db = admin.firestore();

        exports.AddUserRole = functions.auth.user().onCreate(async (authUser) => {
            if (authUser.email) {
                const customClaims = {
                    customer: true,
                };
                try {
                    var _ = await admin
                        .auth()
                        .setCustomUserClaims(authUser.uid, customClaims);
                    return db
                        .collection("roles")
                        .doc(authUser.uid)
                        .set({
                            email: authUser.email,
                            role: customClaims,
                        });
                } catch (error) {
                    console.log(error);
                }
            }
        });

        exports.deleteUser = functions.https.onCall(async (data, context) => {
            if (!context.auth.token.admin) return;
            try {
                var _ = await admin
                    .auth()
                    .deleteUser(uid)
                    .then(() => {
                        console.log("Successfully deleted user");
                    })
                    .catch((error) => {
                        console.log("Error deleting user:", error);
                    });
            } catch (error) {
                console.log("error deleting user", error);
            }
        });
    

Here is some of the client-side code as displayed within the template section:

Answer №1

Make sure to access the UID in your cloud function from the data object.

exports.deleteUser = functions.https.onCall(async (data, context) => {
      if (!context.auth.token.admin) return   
      const {uid} = data;
      if (!uid) return {error: "Please enter an UID"} 
      try {
        // Return the promise from here
        await admin.auth().deleteUser(uid)
        await admin.firestore().collection("profiles").doc(uid).delete()
        console.log("Successfully deleted user");
        return {data: "User deleted"}   
      } catch (error) {
        console.log("error deleting user", error);
        return {error}
      }
    });

Remember to pass the UID from Vue app in an object following the documentation example.

const uid = "uidOfUserToBeDeleted"

var deleteUser = firebase.functions().httpsCallable("deleteUser");
deleteUser({uid}) // Not deleteUser(uid)
  .then((result) => {
    console.log("User delete successfully", result);
  })

The issue might be on your frontend. Where is uid defined? If it's an admin trying to delete a user, ensure you fetch the UID from your input field instead of hardcoding it like in the example above.

Is the doc.id representing the UID of the user to be deleted? If so, you should call the function like this deleteUser(doc.id)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues initializing jQuery knob on a jQuery mobile webpage

I'm trying to implement the jquery knob plugin to showcase a circular rating system, but I'm encountering difficulties in getting it to display properly. Below is the code snippet I'm using - can someone please point out what's causing ...

how to bind data to an array in Angular

I recently developed an Angular 7 application that features the capability to dynamically add and remove controls. However, I am facing challenges when it comes to binding the data to the form. In the code snippet below, I am focusing on the process of ad ...

Troubleshooting: Issues with accessing object properties in a function in AngularJS

In my controller, I have a function that checks the day and changes the isOpen property of an object based on the time. The object is retrieved using the code snippet below: $http.get('js/data.json').success(function(data) { $scope.locations = ...

Unfortunately, I am unable to utilize historical redirection in React

When an axios request is successfully completed, I want to redirect. However, I am encountering an error that looks like this: Below is the code snippet: import React, { useState, Fragment } from "react"; import Sidebar from "../../User/Sid ...

Different methods of displaying the next image from a URL without explicitly setting the dimensions

I am attempting to display an image in Next.js without specifying the width and height by using import Image from 'next/image';. It should be noted that the image is sourced from a URL, not a specific folder within the project. <Image si ...

Is there a way to use axios in Vue and Laravel to easily upload both an image file and data object?

I'm having trouble uploading an image as well as additional text and numeric data fields to a MySQL database using Vue, Laravel, and Axios. Below is the code for the method in my Vue component: addProductToShop() { const imageData = this.$ref ...

Nullable Object in Vue 3 Composition API

I am utilizing the Vue 3 Composition api along with Typescript to create pinch zoom functionality using the HammerJS package. In my Vue application, I am attempting to replicate a functional example implemented in JavaScript from CodePen: https://codepen. ...

Recursive array generation

Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver correspon ...

What steps can be taken to solve the JavaScript error provided below?

My objective is to create a new variable called theRightSide that points to the right side div. var theRightSide = document.getElementById("rightSide"); Once all the images are added to the leftSide div, I need to use cloneNode(true) to copy the left ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

Searching in real-time using Vue.js with multiple parameters

Is there a way to implement a real-time search feature using vue, where the API requires 3 parameters - select option 1, select option 2, and text input field? For instance, you can use the following format for the API link: http://example.com/api/?para ...

Creating packing features specifically designed for resolution within a reusable module

I've decided to revamp my Angular application based on John Papa's style guide (well, mostly) and my main focus is on improving modularity. The stumbling block I've encountered is with route resolves. So far, I've been using a global ap ...

Is it possible to declare language features in Typescript? For example, changing `!variable` to `no variable`

Can Typescript language features be declared within the app's source code? I want to enhance code clarity by implementing a small feature. Modified Null Test if (no userDetails) { // handle null } This new null test syntax is a little more conc ...

Database storing incorrect date values

After successfully displaying the current year and month in a textbox, an issue arises when submitting the data to the database. Instead of the expected value from the textbox, it defaults to 2014. What could be causing this discrepancy? function YearM ...

Receiving encoded characters in the response

URL: I have encountered an issue where I am trying to retrieve the PDF file from the URL above using code. In tools like Postman or Insomnia, I am able to see the output as expected in PDF format. However, when I attempt it with code, I am receiving rando ...

What is the best way to display a unique modal on every tab?

I'm facing an issue where I am attempting to trigger a modal on each tab item, however the modal only opens on the initial tab. Clicking on any other item results in the modal opening on the first tab instead. Additionally, when I add new items, I am ...

Execute location.replace when the "control" key is pressed

document.addEventListener('keydown', (event) => { var name = event.key; var code = event.code; if (name === 'Control') { location.replace(classroom.google.com) } if (event.ctrlKey) { alert(`Combinatio ...

Uncover the content of a base64 encoded string and convert it into

A JSON response has been linked on the user's request to retrieve an excel document. The structure of the response is as follows: { "format": // file extn ----only xls "docTitle": //file name "document" :// base 64 encoded data } The attem ...

The functionality of Bootstrap tooltips becomes disabled as soon as any element on the page is clicked

When initializing Bootstrap tooltips on my page, I follow this approach <script> $(document).ready(function () { $(function () { $('[data-toggle="tooltip"]').tooltip(); }); }); </script> A questio ...

Is there a JavaScript/jQuery timer for re-invoking a method?

Currently, I am developing a basic animation with jQuery that utilizes the hover method. The issue arises when a user hovers over the same image twice, causing the method to be re-invoked. Any recommendations on how to implement a "timer" to prevent the ...