Bulk delete users in Fireabse

Firebase is nice google owned service that lets you use database right from the browser, not much need for creating your own APIs. It is NoSQL type of DBs and you are responsible for building your indexes .. but this is not the point of this topic. It turns out that from the Authentication section it is not possible to bulk delete users. I have let the signInAnonymosly while testing - and only to realize after some months that there are more than 800 users.. most of them just empty. It would be crazy to manually click and delete each of this users.

A hackish way to do this is via the node firebase-admin package. After installing and configuring the private key, I wrote the following script:

var admin = require("firebase-admin");

var serviceAccount = require("./admin_private_key/racket-tournaments-firebase-adminsdk-fheco-949023672f.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://racket-tournaments.firebaseio.com"
});


const UIDs_to_delete = require("./UIDs_to_delete.json")
console.log(UIDs_to_delete)

Promise.all(
    UIDs_to_delete.map(deleteUser)
)


function deleteUser(uid) {
    return new Promise( (s,r)=>{
        admin.auth()
            .getUser(uid)
            .then(function (userRecord) {
                // See the UserRecord reference doc for the contents of userRecord.
                if (!userRecord.displayName) {
                    // console.log("Successfully fetched user data:", userRecord.toJSON());
                    admin.auth()
                        .deleteUser(uid)
                        .then( ()=>{
                            s()
                        })
                        .catch( (error)=>{
                            console.log("Error fetching user data:", error);                            
                            s(error)
                        })
                }
            })
            .catch(function (error) {
                console.log("Error fetching user data:", error);
                s(error);
            });
    })
}
This function expects the list of UID to be in the file "./UIDs_to_delete.json". But how to get those UID.. The easiest way I could think of is from the browser console with some jQuery scraping. The steps to follow:
  1. Navigate to the Authentication section
  2. Click to show 250 items at once - i.e. we want to scrape as much as possible
  3. Open the browser console and paste the following script:
uids = []
$(".a12n-user-uid ng-transclude").each( (i,e)=>{ uids.push( e.innerText ) })
JSON.stringify(uids, null, 2)
There you have it - in the console you have the nicely formatted list of up to 250 UIDs. Paste them into the file and run the script.

Comments

Popular posts from this blog

Data types: Backend DB architecture

Node.js: Optimisations on parsing large JSON file

Back to teaching