19

If an admin has created a user account in the Firebase Console, after this user has signed in, is it possible to retrieve the 'created' date of the user?

PS Big vote for Firebase to add more admin controls programmatically, for user management.

halfer
  • 19,824
  • 17
  • 99
  • 186
Josh Kahane
  • 16,765
  • 45
  • 140
  • 253
  • You tagged with [firebase-database], but I don't see how this is related. Can you update to make the relation more clear or remove that tag? – Frank van Puffelen Jun 22 '16 at 00:57
  • Hi Frank, I didn't actually put these tags on, I believe a mod must have adjusted them to this. I would say a large part of Firebase user management is part of the database though, Firebase themselves suggest that user records beyond an email and password should be stored for example at a /users node. – Josh Kahane Jun 22 '16 at 11:24
  • 1
    Hi Josh. We are taking internally your vote for adding more programmatic admin controls :) – Alfonso Gomez Jordana Manas Jun 22 '16 at 17:23
  • 1
    It's possible now with `Auth.auth().currentUser.metadata.creationDate` – Louis Ameline Jun 26 '20 at 14:42

8 Answers8

14

On the Firebase client web API you can get the user's account creation date with:

var user = firebase.auth().currentUser;
var signupDate = new Date(user.metadata.creationTime);

Link to unhelpful documentation.

Robin Stewart
  • 3,147
  • 20
  • 29
  • Is this code standard ECMAScript, or does it depend on implementation-specific functionality? From [this MDN article](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date_time_string_format), it seems that the only standard format supported by `new Date` / `Date.parse` is a simplification of ISO 8601, e.g. `2011-10-10T14:48:00`. Firebase Auth time is in "UTC Date string" form e. g. `Sat, 03 Feb 2001 04:05:06 GMT`. – cubuspl42 Oct 04 '21 at 14:27
  • @cubuspl42 Good point. I've tested that this works in recent versions of Chrome, Safari, Firefox, and Edge. But you could use a third-party date parser if necessary. – Robin Stewart Oct 05 '21 at 18:04
  • BTW, there is also a completely undocumented `a` parameter that is a unix timestamp. So you can use: `(new Date(parseInt(user.metadata.a))` However, relying on an undocumented property in the Firebase payload seemed much riskier than using long-standing date parsing capabilities that just aren't technically in the standards. – Robin Stewart Oct 05 '21 at 18:09
  • I agree with you. On the other hand, the mentioned capabilities aren't just missing in the standard; I haven't found a single piece of documentation (even implementation-provided) that proves that such format is supported... Like you suggested, I ended up using third party library. – cubuspl42 Oct 05 '21 at 18:23
12

Currently AFAIK, getting creation date is only possible with the Admin Node.js SDK:

admin.auth().getUser(uid)
  .then(function(userRecord) {
    console.log("Creation time:", userRecord.metadata.creationTime);
  });

Documentation: https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth.usermetadata.md#usermetadatacreationtime

Ryan
  • 1,372
  • 14
  • 20
  • how to convert the UTC timestamp to local timestamp for creationTime? – Rachit Rawat Aug 18 '19 at 19:05
  • Documentation is updated. Check https://firebase.google.com/docs/reference/admin/python/firebase_admin.auth#get_user . In python just go with `_` everywhere (`user.user_medadata.creation_timestamp`) – mrj Jan 23 '20 at 10:11
7

Admin backend SDK

This is now achievable with the following in case you are trying to get the info on a server side application.

admin.auth().getUser(uid).then(user => {
    console.log(user.metadata.creationTime);
});

Client side Applications

Despite you are able to see this information on firebase Auth console you wont be able to retrieve this data on the application side as you can see in the documentation.

If you want to use this data on your application you'll need to store it under your database on somethink like databaseRoot/user/userUid/createdAt. So make sure you are creating this node whenever creating a new user such as in this question.

adolfosrs
  • 9,286
  • 5
  • 39
  • 67
3

As of this writing, Angularfire2 is at release candidate version 5. The Javascript API makes it possible to retrieve both the creation date and the last login date of the currently authenticated user.

Example:

this.afAuth.auth.onAuthStateChanged(user => {
  const createdAt = user.metadata.creationTime
  const lastLogin = user.metadata.lastSignInTime
  const a = user.metadata['a'] // <- Typescript does not allow '.' operator
  const b = user.metadata['b'] // <- Typescript does not allow '.' operator

  console.log(`${ user.email } was created ${ createdAt } (${ a }).`)
  console.log(`${ user.email } last logged in ${ lastLogin } (${ b }).`)
})

Though not listed as formal properties, a and b yield the Date objects for the creation and last login dates, respectively, while creationTime and lastSignInTime are the same as GMT string values.

eppineda
  • 667
  • 3
  • 19
2

This function will iterate through all of your users and record there creationDate under the users/$uid/company location

const iterateAllUsers = function () {
  const prom = db.ref('/users').once('value').then(
    (snap) => {
      const promArray = [];
      const users = snap.val();

      Object.keys(users).forEach((user) => {
        promArray.push(getUIDCreationDate(user));
      });
      return Promise.all(promArray);
    });
  return prom;
}

const getUIDCreationDate = function (uid) {

  const prom = fb.getUser(uid)
    .then(function (userRecord) {
      const prom2 = db.ref(`/users/${uid}/company`).update({ creationDate: userRecord.metadata.createdAt }).then((success) => console.log(success)).catch((error) => console.log(error));
      return prom2;
    }).catch(
    error => {
      console.log(JSON.stringify(error))
    });
  return prom;
}
Sean Smith
  • 41
  • 2
1

There is a way of getting it... When you get a firebase.User - usually from some code such as:

this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider()).then(
  (userCredential) => {//do something with user - notice that this is a user credential.
});

anyways, inside this userCredential there is the user and if you do

let myObj = JSON.parse(JSON.stringify(userCredential.user);

you are going to see that you can access the createdAt field

myObj.createdAt // somenumber = time in miliseconds since 1970

So to access it

let myDate: Date = new Date();
myDate.setTime(+myObj.createdAt); //the + is important, to make sure it converts to number
console.log("CREATED AT = " + myDate.toString() );

VOILA!

Emilio Maciel
  • 203
  • 2
  • 9
1

As of Aug 2021, console.dir(user) gives:

    {
"uid": "2Sf.......PH2",
"anonymous": true,
"isAnonymous": true,
"providers": [],
"photoURL": null,
"email": null,
"emailVerified": false,
"displayName": null,
"phoneNumber": null,
"refreshToken": "ACz.......7tgTs",
"metadata": {
"creationTimestamp": "2020-07-08T18:32:09.701Z",
"lastSignInTimestamp": "2020-07-08T18:32:09.701Z"
}
}

So, user.metadata.creationTimestamp will give the creation date.

Ed Jones
  • 653
  • 1
  • 4
  • 19
0

I used this function for my Xamarin Android project to get the date and time which worked for me:

   public DateTime GetCurrentUserCreatedDate()
    {
        var metadata = Firebase.Auth.FirebaseAuth.Instance.CurrentUser.Metadata;
        var creationTimestamp = metadata?.CreationTimestamp;
        var creationDate = DateTimeOffset.FromUnixTimeSeconds(creationTimestamp.Value / 1000).DateTime;
        return creationDate;
    }
Usman Mahmood
  • 536
  • 4
  • 7