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

Sliding with JavaScript

I'm looking to develop a unique web interface where users can divide a "timeline" into multiple segments. Start|-----------------------------|End ^flag one ^flag two Users should be able to add customizable flags and adjust their position ...

Triggering a function in response to a click

I'm encountering an issue with calling a callback inside a click event. Initially, I am attaching the click event to each table row. jQuery(tr).click(function (event) { var that = this; A(event, that, function () { var $gantt_containe ...

Using XMLHttpRequest with gzip compression

Utilizing the request module in node.js makes it simple to create a request that can retrieve and correctly decompress compressed data from the source: var request = require('request'); var requestOptions = { url: 'http://whatever.com/g ...

Retrieving all users in Sqlite database with a specific value

I am looking to identify and access each user who has a specific value in their row. Here is an example code snippet of what I want: sql.prepare("SELECT * FROM raid WHERE raid1 > 0 AND NOT id='685337576810610734'").get().forEach(async (user) ...

Enhancing website functionality with Regex in Javascript

So, here is the code I am working with: var patt = new RegExp("/.+/g"); var device_id = patt.exec("javascript:project_id:256, device_id:2232"); Surprisingly, after running the above code, the value of device_id is empty and I can't seem to figure ou ...

Tips for positioning a div next to an input box when it is in focus

I am working on a scenario where I have used CSS to extend the search box when focused. The idea is that when the search box is focused, it should decrease in size and a cancel button should appear next to it. This is the CSS code I am using: .clrble .fr ...

In JavaScript, not all elements are removed in a single iteration, even if the condition is consistently met

I'm currently attempting to compare two arrays containing multiple objects and remove elements based on a condition. To my surprise, while testing in Chrome's console, I noticed that the first array (arr1) is not being emptied even though I am us ...

Developing unit tests for a module responsible for generating Json REST services

Just completed working on https://github.com/mercmobily/JsonRestStores. Feeling a bit nervous since I haven't written any unit tests yet. This module is quite complex to test: it enables the creation of Json REST stores and direct interaction with th ...

What is the best way to display an Error 404 page in a statically rendered client-side page using Next.js?

import { onAuthStateChanged } from "firebase/auth"; import Link from "next/link"; import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import { auth } from "../../lib/firebase&qu ...

Simple JavaScript validation for inputting names

Hey there, I'm a beginner in javascript and I am struggling with a simple input validation using else if statements. Every time I run the code, it goes directly to the else condition. Can someone please assist me? <!DOCTYPE html> <html lang=& ...

The function chrome.notifications.create() is producing incorrect notification IDs upon clicking

Greetings for my first post here. I've been struggling with an issue in a personal project lately. I remember coming across a similar topic on this forum before, but now I can't seem to find it. As far as I recall, the question went unanswered. ...

What led to the decision for the two distinct chart elements to merge into a single container?

In the process of creating a dashboard using React.js and d3.js, I encountered an interesting issue that perplexed me for quite some time. Below is the Scatterplot.js code written in d3.js: import React, { Component } from "react" import * as d3 from "d3 ...

Navigating through the Document Object Model within a table

I'm working with an HTML table that contains a delete button in each row's last column. When the button is clicked, I want to delete the entire row. However, my current code only deletes the button itself and not the entire row: var buttons = do ...

Is it possible to use a marker with label in conjunction with a google maps circle?

In my mapping project, I use different markers for various scenarios. A regular marker represents an individual item, a customized marker represents a region containing multiple items, and a circle marker is used when there are too many items in one region ...

Adding a dynamic route prefix in Nuxt.js: A step-by-step guide

Looking to integrate a dynamic language feature using an API. The API will provide a list of languages, and each language except "en" should have a route prefix. For instance: en: https://mynuxt.com/hotel/paris-hotel de: https://mynuxt.com/de/hotel/pari ...

How can a regular number be used to create an instance of BigInteger in jsbn.js?

I attempted both methods: const num1 = new BigNumber(5); And const num2 = new BigNumber(7, 10); However, I encountered the following error: Error: 'undefined' is not an object (evaluating 'num2.nextBytes') bnpFromNumberjsbn2.js:126 ...

Transferring data between functions within the same controller in AngularJS

I have implemented two functions to handle the timing of a process, one for starting and one for stopping. Here is the code snippet: $scope.start = function(data) { $scope.time = { id: '', mainId: data.id, start: &ap ...

CSS classes designed to mimic JavaScript object attribute-value pairs

I stumbled upon some interesting css class-value combinations within HTML tags. It seems like a specific JavaScript code is interpreting this, but it's something I haven't encountered before. I came across this on www.woothemes.com/flexslider/ (y ...

Step-by-step guide on resolving AngularJS Issue: [$injector:modulerr]

I'm encountering an issue with Angular JS where I'm receiving the following error: jquery.js:7993 Uncaught Error: [$injector:modulerr] Failed to instantiate module application due to: Error: [$injector:nomod] Module 'application' is no ...

Rails Ajax form submission not working

I recently set up a basic Google form on my website and used this website to extract the HTML code for display. However, upon hitting submit, nothing happens - the page seems to be frozen. I'm attempting to redirect the form submission to another page ...