Delete all users from firebase auth console

北慕城南 提交于 2019-11-28 04:53:39

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

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() {
  if ($('[aria-label="Delete account"]').size() == 0) {
    console.log("interval cleared")
    clearInterval(intervalId)
    return
  }
  $('[aria-label="Delete account"]')[0].click();
  setTimeout(function () {
     $(".md-raised:contains(Delete)").click()
  }, 1000);
};

intervalId = setInterval(clearFunction, 3000)

Just run it in developer tools

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.

Here is my bicycle: 😄

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.

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.

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

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

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();

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());
});

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)

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")

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!