Extract Created date and last login from firebase authentication using Python

Question:

Currently my python code gets the user id and email of all users from firebase authentication using the firebase admin SDK, however I am unable find the correct syntax to extract the user metadata such as the created and last login date/time (which according to the documentation is in milliseconds). There are a few documentation that shows ways to do this, but it is not working for me.

My code:

from firebase_admin import credentials
from firebase_admin import auth

cred=credentials.Certificate('firebasesdk.json')
firebase_admin.initialize_app(cred, {
    "databaseURL": "myurl",
})

page = auth.list_users()
    while page:
        for user in page.users:
            print('User email: ' + user.email)
            print('User id: ' + user.uid)

I tried using user.metadata.creationTimeand user.madata.getLastSignInTimestamp and but it does not work with python. I was looking through this post regarding this issue.

Answers:

It looks like the ExportedUsers result for list_users does not include the metadata for the users. In that case you’ll need to call get_user(...) for each UID in the result to get the full UserRecord, and then find the timestamps in the metadata.

Answered By: Frank van Puffelen

The correct syntax is user.metadata.creation_timestamp and user.metadata.last_sign_in_timestamp. See API reference: https://firebase.google.com/docs/reference/admin/python/firebase_admin.auth#firebase_admin.auth.UserMetadata

Answered By: Hiranya Jayathilaka

To get creationTime and getLastSignInTimeStamp, you can access creation_timestamp and last_sign_in_timestamp from the user_metadata field. For example

from firebase_admin import auth

page = auth.list_users()
    while page:
        for user in page.users:
            print('User creation time: ' + user.user_metadata.creation_timestamp)
            print('User last sign in time: ' + user.user_metadata.last_sign_in_timestamp)
        page = page.get_next_page()

or

from firebase_admin import auth

for user in auth.list_users().iterate_all():
    print('User creation time: ' + user.user_metadata.creation_timestamp)
    print('User last sign in time: ' + user.user_metadata.last_sign_in_timestamp)

Each timestamp is an integer representing milliseconds since the epoch.

More info:

user is a ExportedUserRecord which inherits from UserRecord

user_metadata is UserMetadata

Answered By: S. Czop