Home > Software engineering >  How to delete firebase auth users that have not recently signed in?
How to delete firebase auth users that have not recently signed in?

Time:01-20

We have an app with ~50K users and we would like to delete (from firebase auth) everyone who hasn't signed in since January 1st, 2023.

Using cloud functions, I can successfully delete any specific user. However, I can't figure out how to access lastSignInTime.

This is the code so far, but I can't isolate SignInTime

exports.deleteAuthUser = functions.https.onCall(async (data, context) => {
  admin.auth().getUser(data.uid)
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    // console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
    // console.log(userRecord.metadata);
    console.log(userRecord.metadata);
    let time = userRecord.metadata.lastSignInTime.getTime()
    console.log(time)
  })
  .catch((error) => {
    console.log('Error fetching user data:', error);
  });
})

This is userRecord.metadata { UserMetaData [ lastSignInTime: xxx ] }

enter image description here

Also, once I can access lastSignInTime, my plan is to covert it with getTime() and then see if it's greater than 1/1/23.getTime()

Thanks!

CodePudding user response:

Seems you are deleting each user individually by checking last login time.Instead you can use admin.auth().listUsers(100) to get the users in small chunks as doing this operation on all 50K users may hit the timeout limit of firebase functions.

My Answer is based on this documentations there is also a section about listing users batch wise.

I have used below code to list 100 users and deleted users.Although I have tested this with less samples only, it worked. And I will recommend you to use this in Batches. And also I used onRequest function here instead of onCall:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
exports.deleteAuthUser = functions.https.onRequest(async (req, res) => {
  console.log(req, res);
  admin.auth().listUsers(100)
      .then((listUsersResult) => {
        listUsersResult.users.forEach(async (userRecord) => {
          const lastSignInTime = userRecord.metadata.lastSignInTime;
          const targetDate = new Date("2023-01-17T00:00:00.000Z").getTime(); //change target date as per your needs
          const tobeCompared = new Date(lastSignInTime).getTime(); //used javascript getTime
          if (tobeCompared < targetDate) {
            await admin.auth().deleteUser(userRecord.uid)
                .then(() => {
                  console.log(`Successfully deleted user ${userRecord.uid}`);
                })
                .catch((error) => {
                  console.log(`Error deleting user ${userRecord.uid}`, error);
                });
          } else {
            console.log(`User ${userRecord.uid} 
            last signed in after January 17, 2023. Not deleting.`);
          }
        });
      })
      .catch((error) => {
        console.log("Error fetching users:", error);
      });
});

There is also this thread which uses a different approach.

The above code will only delete the users but not their data. To achieve that you can use Delete User Data extension. For more details on how to use it i recommend to go through the documentation

  • Related