Michael m.
Michael m.

Reputation: 191

How to check when firebase user was created?

Im using a schedule function to delete unverified users. The schedule function runs every 24 hours. Now the Problem that I have is : Lets say a user created his account 3 minutes ago and did not verify his email address yet. And then the functions runs and delete his/her/it Account. What I want is to give the user lets say 5 hours to verify his account . So my question is how can I check that in my function ? Here's my function

import * as functions from "firebase-functions";
import admin from "firebase-admin";

export default  functions.pubsub.schedule('every 24 hours').onRun(async(context) => {
    console.log('This will be run every 24 hours!');
    const users = []
    const listAllUsers = (nextPageToken) => {
        // List batch of users, 1000 at a time.
        return admin.auth().listUsers(1000, nextPageToken).then((listUsersResult) => {
            listUsersResult.users.forEach((userRecord) => {
                users.push(userRecord)
            });
            if (listUsersResult.pageToken) {
                // List next batch of users.
                listAllUsers(listUsersResult.pageToken);
            }
        }).catch((error) => {
            const functions = require("firebase-functions");

            functions.logger.error("Hello from info. Here's an problem:", error);
        });
    };
    // Start listing users from the beginning, 1000 at a time.
    await listAllUsers();
    const unVerifiedUsers = users.filter((user) => !user.emailVerified).map((user) => user.uid)

    //DELETING USERS
    return admin.auth().deleteUsers(unVerifiedUsers).then((deleteUsersResult) => {
        console.log(`Successfully deleted ${deleteUsersResult.successCount} users`);
        console.log(`Failed to delete ${deleteUsersResult.failureCount} users`);
        deleteUsersResult.errors.forEach((err) => {
            console.log(err.error.toJSON());
        });
        return true
    }).catch((error) => {
        const functions = require("firebase-functions");

    functions.logger.error("Hello from info. Here's an problem:", error);
        return false
    });
});

If any question please let me know !

Upvotes: 0

Views: 409

Answers (2)

Oskar
Oskar

Reputation: 3702

This works fine for me:

import { auth } from 'firebase-admin'

// ...your function

let uid = request.auth?.uid
let userCreation = await auth()
    .getUser(uid)
    .then((user) => {
        return user.metadata.creationTime
    })

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317740

That's not possible with the Firebase Auth APIs. You will have to record the time on your own in a separate database, and using that database to find out the time you need to know.

Upvotes: 0

Related Questions