83

Is there an easy way to delete all registered users from firebase console? For example, I created a hundred users from my development environment, and now I want to delete all of them.

benomatis
  • 5,536
  • 7
  • 36
  • 59
Maximus S
  • 10,759
  • 19
  • 75
  • 154

30 Answers30

115

As in updated answer, you can probably use firebase admin tools now, but if you don't want – here is a bit more solid javascript to remove users in the web:

var intervalId;

var clearFunction = function() {
  var size = $('[aria-label="Delete account"]').size()
  if (size == 0) {
    console.log("interval cleared")
    clearInterval(intervalId)
    return
  }
  var index = Math.floor(Math.random() * size)
  $('[aria-label="Delete account"]')[index].click();
  setTimeout(function () {
     $(".md-raised:contains(Delete)").click()
  }, 1000);
};

intervalId = setInterval(clearFunction, 300)

Just run it in developer tools

maclir
  • 3,218
  • 26
  • 39
AAverin
  • 3,014
  • 3
  • 27
  • 32
77

For the new Firebase update

Try this code for the latest Firebase update. Open the console, paste this code and hit enter!!!

setInterval(() => {
    document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base')[0].click()
    Array.from(document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted')).at(-1).click();
    document.getElementsByClassName('confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn')[0].click()
}, 1000)
Mišo
  • 2,327
  • 1
  • 23
  • 25
Yaman KATBY
  • 1,814
  • 10
  • 24
44

Because I'm pretty lazy at clicking buttons and elements in the UI, I set up a small client script:

$('[aria-label="Delete account"]').click()
setTimeout(function () {
   $(".md-raised:contains(Delete)").click()
}, 1000);

You may need to run it multiple times, but it is much better than wasting the time clicking things on the screen manually.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
30

Fully working solution using Firebase Admin SDK

Using the Firebase Admin SDK is really easy and the recommended way to perform such tasks on your Firebase data. This solution is unlike the other makeshift solutions using the developer console.

I just put together a Node.js script to delete all users in your Firebase authentication. I have already tested it by deleting ~10000 users. I simply ran the following Node.js code.

To setup Firebase Admin SDK

Create a new folder. Run the following in terminal

npm init
sudo npm install firebase-admin --save

Now create an index.js file in this folder.

Steps to follow:

  • Go to your Firebase project -> Project Settings -> Service Accounts.
  • Click on Generate new Private Key to download the JSON file. Copy the path to JSON file and replace it in the code below in the path to service accounts private key json file.
  • Also, copy the databaseURL from the settings page. Replace it in the code.
  • Copy and paste the code in index.js.
  • Run in terminal node index.js. Watch the mayhem!
var admin = require('firebase-admin');

var serviceAccount = require("/path/to/service/accounts/private/key/json/file");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "/url/to/your/database"
});

function deleteUser(uid) {
    admin.auth().deleteUser(uid)
        .then(function() {
            console.log('Successfully deleted user', uid);
        })
        .catch(function(error) {
            console.log('Error deleting user:', error);
        });
}

function getAllUsers(nextPageToken) {
    admin.auth().listUsers(100, nextPageToken)
        .then(function(listUsersResult) {
            listUsersResult.users.forEach(function(userRecord) {
                uid = userRecord.toJSON().uid;
                deleteUser(uid);
            });
            if (listUsersResult.pageToken) {
                getAllUsers(listUsersResult.pageToken);
            }
        })
        .catch(function(error) {
            console.log('Error listing users:', error);
        });
}

getAllUsers();
Sunit Gautam
  • 5,495
  • 2
  • 18
  • 31
27
setInterval(() => {
  $('[aria-label="Delete account"]').first().click()
  setTimeout(()=>{
    $(".md-raised:contains(Delete)").click()
  }, 100)
}, 2000);

designed to avoid calling delete endpoint very often, since google fails with 404 error.

iDecode
  • 22,623
  • 19
  • 99
  • 186
Eugene Hauptmann
  • 1,255
  • 12
  • 16
20

firebaser here

Update 2016-11-08 original answer below

We just released the Firebase Admin SDK, which supports administrative use-cases, such as deleting a user account without requiring that user to sign in first.

original answer

There is currently no API in Firebase Authentication to delete a user without requiring that user to sign in. We know this limits the usability of our API and are working to add such functionality in a future release. But as usual, we don't provide specific timelines for when the feature will be available.

For the moment your only work arounds are to:

  • sign in as each test user in the app and delete the user from there
  • delete each user in turn from the Firebase Console
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 24
    Can you please consider removing the 'Are you sure prompt' in the Firebase Console if you 'Shift' + click 'Delete account'. This would mimic the behaviour in the database and would significantly speed things up. – DrZaphod Oct 13 '16 at 10:02
  • Can I "sign in as each test user" from appengine , without browser? Can I delete users from app engine directly somehow or via some web services? – makkasi Nov 01 '16 at 13:35
  • in the NodeJs firebase-admin SDK is there no way to get all users then for each user `admin.auth().deleteUser(uid);` – Snewedon Nov 08 '16 at 03:53
  • @Frank van Puffelen I see there is not python admin SDK. Is there some way to use the nodeJS admin SDK inside python. – makkasi Feb 24 '17 at 08:23
  • Am glad to know this is now possible via firebase admin sdk. Would be cool to know if these can also be uploaded and used as google https functions? TIA! – raiser00 Dec 27 '17 at 15:43
7

Slightly increased your helper script.

German firebase site version:

$('[aria-label="Nutzermenü öffnen"]').click();
$('[aria-label="Konto löschen"]').click();
for (i = 0; i < 20; i++) {
  setTimeout(() => {
    $('.md-raised:contains(Löschen)').click();
  }, i * 200);
}

For the english version just replace the text. This way you can delete 20 or more users once executed.

5

Used this code successfully on 11/16/2020:

setInterval(function () {
    $('[aria-label="View more options"]')[0].click()
    document.querySelectorAll('.mat-menu-item')[2].click()
    document.querySelector('.confirm-button').click()
}, 1000);
Caconde
  • 4,177
  • 7
  • 35
  • 32
DaBo
  • 51
  • 1
  • 1
  • If you want to get possible rep for your answer then provide substantial more info to boos quality of your answer. 15 answer were before you... – ZF007 Nov 16 '20 at 21:43
5

Tested at 10 Oct 2021

This will click on the last button in the context menu which is always the Delete button, so it works on all account types
setInterval(() => {
    document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base')[0].click()
    var buttons = document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted');
    buttons.item(buttons.length - 1).click();
    document.getElementsByClassName('confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn')[0].click()
}, 1000);
Ahmed Fwela
  • 955
  • 1
  • 13
  • 32
4
setInterval(() => {
  if ($('[aria-label="Delete account"]').length > 0) {
    $('[aria-label="Delete account"]').first().click()
    setTimeout(()=>{
      $(".md-raised:contains(Delete)").click()
    }, 100)
  } else {
    $('[aria-label="Reload"]').first().click()
  }
}, 2000);

Try this one. It's an update to @www.eugenehp.tk answer above that takes into account the need to refresh the page if you have more than one page of entries.

Chris
  • 955
  • 15
  • 20
4

Updated 03/2022 working (with load next records page)

setInterval(() => {
        var RecordsCount = document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base').length;
        if (RecordsCount>0)
        {
            document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base')[0].click()
            let deleteButtonPosition = document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted').length - 1
            document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted')[deleteButtonPosition].click()
            document.getElementsByClassName('confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn')[0].click()
        }
        else
        {
              //reload more records
              $('[aria-label="Reload"]').first().click();
        }
}, 800);
Flying light
  • 183
  • 2
  • 11
  • You helped me delete 50k accounts. Thank you! The only problem with the script was that I had to increase the delay for the last 2k accounts to 1 second (1000 ms). – spasbil May 05 '22 at 13:06
4

This code still works as by June 20, 2023.

Following are the steps to delete all users in one go.

  1. Open Firebase Authentication
  2. Right Click and choose Inspect
  3. In the developer tools, tap the Console tab
  4. Paste this code there
setInterval(() => {
      document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base')[0].click()
      let deleteButtonPosition = document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted').length - 1
      document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted')[deleteButtonPosition].click()
      document.getElementsByClassName('confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn')[0].click()
}, 1000)
  1. Hit Enter

This will start deleting your users.

Taimoor Arif
  • 750
  • 3
  • 19
3

Well, I used this script to delete all users at once in Firebase console:

$('[aria-label="Delete account"]').each(function() {
  $(this).click();
  $('[ng-click="controller.submit()"]').click()
})

https://console.firebase.google.com/project/YOUR_PROJECT_NAME/authentication/users

Rafael Garcia
  • 361
  • 3
  • 14
2

Just created a script to run into console when the Firebase Authentication window is opened. Step 1: Go to the Authentication Tab of your Firebase Project

Step 2: Press Ctrl + Shift + i to go to browser console

Step 3: Copy the following code and paste it into the console.



(function delScript() {
  const allRowNodes = document.querySelectorAll("tbody tr");
  if (!allRowNodes || !allRowNodes.length) {
    console.log("No Accounts to delete ");
    return null;
  }
  allRowNodes.forEach((curRowNode, idx) => {
    setTimeout(() => {
      curRowNode.querySelector(".edit-account-button").click();
      setTimeout(() => {
        document.querySelector("button.mat-menu-item:nth-child(3)").click();
        setTimeout(() => {
          document
            .querySelector("fire-dialog-actions button:nth-child(2)")
            .click();
          setTimeout(() => {
            const backdrop = document.querySelector(
              ".cdk-overlay-backdrop-showing"
            );
            backdrop.click();
          }, 1200);
        }, idx * 1600);
      }, idx * 800);
    }, idx * 800);
  });
})();


1

Russian version

var intervalId;

var clearFunction = function() {
if ($('[aria-label="Удаление аккаунта"]').size() == 0) {
console.log("interval cleared")
clearInterval(intervalId)
return
}
$('[aria-label="Удаление аккаунта"]')[0].click();
setTimeout(function () {
$('[ng-click="controller.submit()"]').click()
}, 1000);
};

intervalId = setInterval(clearFunction, 3000)
1

A solution that worked for me was to create a separate file and import my firebase-admin and simply run the following:

const admin = require('./firebase_admin');

const listAllUsers = () => {
  console.log('list all users');
  // List batch of users, 1000 at a time.
  admin.auth().listUsers(1000)
    .then((listUsersResult) => {
      listUsersResult.users.forEach((userRecord) => {
        const user = userRecord.toJSON();
        admin
          .auth()
          .deleteUser(user.uid)
          .then(() => {
            console.log('successfully deleted user');
          })
          .catch((err) => {
            console.error('error deleting user: ', err);
          });
      });
      if (listUsersResult.pageToken) {
        // List next batch of users.
        listAllUsers(listUsersResult.pageToken);
      }
    })
    .catch((error) => {
      console.log('Error listing users:', error);
    });
};
// Start listing users from the beginning, 1000 at a time.
listAllUsers();

The concept here is that we want to retrieve all the users from our user auth table, then cycle throw and delete them one at a time using the deleteUser admin auth method.

In the terminal, I simply used node to call the function in the file (so let's say the filename is delete_users.js, I just called node delete_users.js and the listUsers function was invoked.

Hope this helps.

Ariel Salem
  • 357
  • 3
  • 12
  • Thanks, but a few things I had to go add on. Required the addition of firebase-functions and also a private key to give the script credentials to run. Followed these steps: https://firebase.google.com/docs/admin/setup – howdoyouturnthison Nov 30 '19 at 15:33
1

French version,

var intervalId;

var clearFunction = function() {
  if ($('[aria-label="Supprimer le compte"]').size() == 0) {
    console.log("interval cleared")
    clearInterval(intervalId)
    return
  }
  $('[aria-label="Supprimer le compte"]')[0].click();
  setTimeout(function () {
     $(".md-raised:contains(Supprimer)").click()
  }, 1000);
};

intervalId = setInterval(clearFunction, 3000)

PS: if you are not web developer and "Execute in tools developer" means nothing to you, here the procedure.

  • Open your firebase authentication/users page with Chrome
  • Press control + shif+ J
  • In the console tab, paste this code and press enter.

  • If the language matched with the code your paste, account will start to be deleted.

1

if u have anonymous accounts

setInterval(() => {
    document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base')[0].click()
    document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted')[document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted').length === 3 ? 2 : 1].click()
    document.getElementsByClassName('confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn')[0].click()
}, 1000)
1

Just execute the below script on the console and it will delete all users at once.

$('.edit-account-button').click();

$('.mat-menu-content button:last-child').click()

$('.fire-dialog-actions .confirm-button').click()

1

Updated 2021 working answer

const interval = setInterval(() => {
  if ($('.edit-account-button').length === 0) {
    clearInterval(interval)
  } else {
    $('.edit-account-button').first().click()
    $('button:contains("Delete account")').click()
    $('.confirm-button').click()
  }
}, 1000)

https://gist.github.com/cupcakearmy/8c314b891e6958f26374c0205bac85e9

Nicco
  • 11
  • 2
1

This Works now 17.09.2021

Go to your firebase console, click inspect element and select console and paste this code there.

setInterval(() => {
    document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base')[0].click()
    document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted')[2].click()
    document.getElementsByClassName('confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn')[0].click()
}, 1000)

For authentication types: if you authenticate by mail id use [2] in the second line, if you use mobile authentication use1 in the second line

enter image description here

1

I will just add that if you have many users you need to press the reload button so just make another setInterval:

const reloadButton = document.querySelectorAll("button")[10];
const arr = document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base');

and the setInterval:

setInterval(() => {
if(!arr.length) reloadButton.click()
}, 1000)
Tal Talmon
  • 47
  • 7
0

This might be helpful to some. If you have access to the firebase user console - just save the page as an html and use the following to delete users with node. need to setup firebase-admin

let fs = require('fs'),
  admin = require('firebase-admin'),
  cheerio = require('cheerio');

// initialize firebase admin here
admin.initializeApp({
credential: admin.credential.cert('path/to/serviceAccountKey.json'),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

// use cheerio to load the html file you downloaded
$ = cheerio.load(fs.readFileSync('./yourfirebaseconsole.html'));
$('.a12n-user-uid .fb-table-cell-wrapper').each(function() {
  admin.auth().deleteUser($(this).text());
}).then(() => {
  console.log('successfully delete user');
}).catch((error) => {
  console.log('error occurred ', error);
});

I would recommend doing a dry run of the html parsing logic once on the page using browser by just running this and confirming that only user ids are displayed in the result. In my case this returned all UIDs

$('.a12n-user-uid .fb-table-cell-wrapper').each(function() {
  console.log($(this).text());
});
0

I used it

var openMenuItemForFirstUser = function () {
    const menuItem = $('[ng-click="controller.deleteUser()"]')
    if (menuItem.size()) {
        menuItem[0].classList.add("deletingThisUser")
        menuItem[0].click();
        setTimeout(deleteUser, 10, 0)
    } else {
        console.log("No users found...")
    }
};

var deleteUser = function (t) {
    const confirmButton = $('[ng-click="controller.submit()"]')
    if (confirmButton.size()) {
        console.log("deleting user")
        confirmButton[0].click()
        setTimeout(waitForDeletion, 10, 0)
    } else {
        if (t > 500) console.log("fail trying delete user")
        else setTimeout(deleteUser, 10, parseInt(t) + 1)
    }
}

var waitForDeletion = function (t) {
    const deletingThisUser = $('.deletingThisUser')
    if (deletingThisUser.size()) {
        if (t > 500) console.log("fail wait for deletion")
        else setTimeout(waitForDeletion, 10, parseInt(t) + 1)
    } else {
        setTimeout(openMenuItemForFirstUser, 10)
    }
}

setTimeout(openMenuItemForFirstUser, 1000)
console.log("Deleting all users... Press F5 to cancel it")

thr0w
  • 1,454
  • 3
  • 10
  • 7
0

I tried all the previous, none worked, so I created one for my needs:

setInterval(() => {

  if ($('[aria-label="View more options"]').length > 0) {

    $('[aria-label="View more options"]')[0].click()

    if ($('[role="menuitem"]').length > 0) {

      $('[role="menuitem"]')[1].click()

      if ($('[class="confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn"]').length > 0) {

        $('[class="confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn"]').click()
      }
    }
  }
}, 500);
AndyW58
  • 345
  • 2
  • 6
0

Here's another script that can be used as a bookmarklet. Simply

  1. create a new bookmark (Ctrl-D)
  2. select "more"'
  3. paste the script into the URL input

You can then just click the bookmark to delete all users. The script will stop when there's no more users or you navigate away. If you're not using the english version, update the *Text variables with the corresponding text.

javascript: (function () {
  const deleteText = 'Delete account';
  const deleteConfirmationText = 'Delete';

  const editSelector = '.edit-account-button';
  const deleteSelector = `button:contains(${deleteText})`;
  const deleteConfirmationSelector = `button span:contains(${deleteConfirmationText})`;
  const waitForAnimation = 350;

  const deleteUsers = () => {
    const editAccountButton = $(editSelector).first();

    if (!editAccountButton.size()) {
      console.log('Delete complete.');
      return;
    }

    editAccountButton.first().click();
    setTimeout(() => {
      $(deleteSelector).first().click();
      setTimeout(() => {
        $(deleteConfirmationSelector).first().click();
        setTimeout(() => {
          deleteUsers();
        }, waitForAnimation * 1.5);
      }, waitForAnimation);
    }, waitForAnimation);
  };

  deleteUsers();
})();
uɥƃnɐʌuop
  • 14,022
  • 5
  • 58
  • 61
0

In my project, I had firebaseAdmin hooked up to an emulator for testing. To clear the database before each test I combined the listUsers function with the deleteUser function. Caution you probably don't want to create this type of functionality for a real database.

My code looked like this.

import * as Bluebird from "bluebird"

function clearAllUsers() {
  return Promise.resolve()
    .then(() => admin.auth().listUsers())
    .then((response) => response.users)
    .then((users) =>
      Bluebird.map(users, (user: { uid: string }) =>
        admin.auth().deleteUser(user.uid),
      ),
    );
}

But you could also use async await and accomplish the same thing with

import * as Bluebird from "bluebird"
async function clearAllUsers() {
  const usersResponse = await admin.auth().listUsers();
  const users = usersResponse.users;
  return await Bluebird.map(users, (user: { uid: string }) =>
    admin.auth().deleteUser(user.uid),
  );
}

Also if you do happen to use an emulator for testing, the UI for it comes shipped with a delete all button. see (here)[https://imgur.com/3Xil86I]

jjhiggz
  • 49
  • 4
0

Simple delete all users - ESM

// delete.ts or delete.mjs

import admin from 'firebase-admin';
import cred from './credentials.json';
let firebaseApp = admin.initializeApp({
    credential: admin.credential.cert(cred as admin.ServiceAccount)
});
const listAllUsers = (nextPageToken?: string) => {
    // List batch of users, 1000 at a time.
    admin
        .auth()
        .listUsers(1000, nextPageToken)
        .then(async (listUsersResult) => {
            await admin.auth().deleteUsers(listUsersResult.users.map((u) => u.uid));
            if (listUsersResult.pageToken) {
                // List next batch of users.
                listAllUsers(listUsersResult.pageToken);
            }
        })
        .catch((error) => {
            console.log('Error listing users:', error);
        });
};
listAllUsers();
HerberthObregon
  • 1,811
  • 19
  • 23
0

Working on 2022/02/19

setInterval(() => {
    $('[mattooltip="View more options"]').first().click()
    setTimeout(()=>{
        $(".mat-focus-indicator:contains(Delete)").click()
        setTimeout(()=>{
           $(".mat-warn").click()
        }, 100)
    }, 100)
}, 2000);
TheFlyBiker 420
  • 69
  • 1
  • 13
0

I wanted to improve yaman-katby answer, because I didn't want to press "refresh button" every time the list was empty.


An updated for my answer:

So, if you open multiple windows (no fullscreen mode), and order by different ways, you can delete all your users. But sometimes you will find an error that you erased a user previously.

That why I added times and elementSize variables, to refresh the list and continue deleting the users

let times=0;
let elementSize=0;
setInterval(() => {
    if( (document.getElementsByClassName('no-user-text ng-star-inserted').length > 0) || ( elementSize == document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base').length && times == 3 ) || times == 50 ) {
        times=0;
        elementSize=0;
        document.querySelectorAll('.mat-focus-indicator.mat-mdc-tooltip-trigger.mat-icon-button.mat-button-base[data-test-id="reload-user-button"]')[0].click()
    } else {
      document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base')[0].click();
    let deleteButtonPosition = document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted').length - 1;
    document.getElementsByClassName('mat-focus-indicator mat-menu-item ng-star-inserted')[deleteButtonPosition].click();
    document.getElementsByClassName('confirm-button mat-focus-indicator mat-raised-button mat-button-base mat-warn')[0].click();
        elementSize = document.getElementsByClassName('edit-account-button mat-focus-indicator mat-menu-trigger mat-icon-button mat-button-base').length;
        times++;
    }
}, 1000)