I'm letting users to create account and I want to verify their account (Link by mail) so user A won't register with user's B email address. I need to run a job on Firebase functions that upon every user creation or within time range (to prevent a lot of function activations) after 5 minutes of inactivity, the function will go over the whole db of users and delete the user if he didn't verify his account within the time limit. The time limit should be defined in Firebase Remote Config variable.
What I need to fix is upon user creation, run a cron job AFTER 5 minutes to delete that newly created account if the user didn't verify his account.
Here is the code I have but I can't combine the idea of the two:
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.removeUnveryfiedUser = functions.auth.user().onCreate((user) => {
if(!user.emailVerified) {
console.log('User Not Verified...Starting');
functions.pubsub.schedule('every 5 minutes').onRun(async context => {
// Fetch all user details.
const inactiveUsers = await getInactiveUsers();
deleteInactiveUser(inactiveUsers);
console.log('User cleanup finished');
});
} else {
console.log('User verified?...');
}
});
/**
* Deletes one inactive user from the list.
*/
function deleteInactiveUser(inactiveUsers) {
if (inactiveUsers.length > 0) {
const userToDelete = inactiveUsers.pop();
// Delete the inactive user.
return admin.auth().deleteUser(userToDelete.uid).then(() => {
return console.log('Deleted user account', userToDelete.uid, 'because of inactivity');
}).catch((error) => {
return console.error('Deletion of inactive user account', userToDelete.uid, 'failed:', error);
});
} else {
return null;
}
}
/**
* Returns the list of all inactive users.
*/
async function getInactiveUsers(users = [], nextPageToken) {
const result = await admin.auth().listUsers(1000, nextPageToken);
// Find users that have not veryfied their account after 5 minutes.
const inactiveUsers = result.users.filter(
user => Date.parse(user.metadata.lastSignInTime) < (Date.now() - 5 * 60 * 1000));
// Concat with list of previously found inactive users if there was more than 1000 users.
users = users.concat(inactiveUsers);
// If there are more users to fetch we fetch them.
if (result.pageToken) {
return getInactiveUsers(users, result.pageToken);
}
return users;
}