how to delete anonymous users that last signed in more than certain time from Firebase Authentication in NodeJS Admin SDK?

Viewed 264

from Firebase Authentication, we have table like this, the providers can be email, google, facebook or anonymous

enter image description here

I need to delete all anonymous accounts that last signed in was more than six months ago. I need to query those anonymous accounts and then delete them all.

but I really have no idea how to query all anonymous account that last signed in was more than six months ago using Node JS admin SDK. is it possible? how to do that?

because there is a limit from firebase (100 million anonymous account) from the documentation in here. I may not hit that limit, but I think it is better If I can clean unused anonymous accounts by creating a cron job using cloud scheduler in cloud function

1 Answers

I think I find the solution, I suggest you to read this Firebase official documentation first, to know how to get all users from authentication, there is an explanation there that you need to read. there is no something like query to get data we need, at least right now

I will use Typescript and async/await instead of then/catch and Javascript. but if you use javascript, then you just need to modify the function parameter a little bit

import * as moment from "moment";
const auth = admin.auth();

export const deleteUnusedAnonymousUsers = async function(nextPageToken?: string) {

    // this is a recursive function

    try {

        // get accounts in batches, because the maximum number of users allowed to be listed at a time is 1000
        const listUsersResult = await auth.listUsers(1000, nextPageToken);

        const anonymousUsers = listUsersResult.users.filter((userRecord) => {
            return userRecord.providerData.length == 0;
        });

        const sixMonthAgo = moment().subtract(6, "months").toDate();

        const anonymousThatSignedInMoreThanSixMonthAgo = anonymousUsers.filter((userRecord) => {
            const lastSignInDate = new Date(userRecord.metadata.lastSignInTime);
            return moment(lastSignInDate).isBefore(sixMonthAgo);
        });

        const userUIDs = anonymousThatSignedInMoreThanSixMonthAgo.map((userRecord) => userRecord.uid);

        await auth.deleteUsers(userUIDs);

        if (listUsersResult.pageToken) {
            // List next batch of users.
            deleteUnusedAnonymousUsers(listUsersResult.pageToken);
        }

    } catch (error) {
        console.log(error);
    }

};

usage

deleteUnusedAnonymousUsers();
Related