When does creationTime or lastSignInTime of firebase.auth.UserMetadata returned as null/undefined?

Viewed 145

I bumped into this issue while trying to create user document in Firestore after a new user is signed up using Firebase Authentication.

In user document, I want to include creationTime and lastSignInTime fields but found out that those fields are optional. That means I would have to make those fields in my user document optional as well but I am not quite convinced why they should be optional in the first place. I just cannot think of a case where those fields in metadata of User instance should be set as undefined when it is returned after successful sign up/in using Firebase Auth.

If there's no specific case where they're returned as undefined, I'm planning to make those fields in my user document as required fields, and throw error just in case they are returned as undefined.

For example using react-native-firebase:

try {
  const { user } = await auth().signInAnonymously();
  const {
    metadata: { creationTime, lastSignInTime },
    uid,
  } = user;

  if (creationTime == null) {
    throw new TypeError('creationTime is returned as undefined');
  }
  if (lastSignInTime == null) {
    throw new TypeError('lastSignInTime is returned as undefined');
  }
  await firestore().collection('user').doc(uid).set({ 
    creationTime,
    lastSignInTime,
    // other fields
  });
} catch (error) {
  // handle error
}

But if not, then no choice but to have them as optional as well.

So wrapping up the question, is there any case where creationTime or lastSignInTime is set to undefined/null? Is it safe to just treat them as required fields?

(A similar issue is posted here but it's closed with no answer.)

1 Answers

I'm not sure about creationTime but lastSignInTime can be undefined/null if the sign-up has occurred but the user has not signed in yet. For example the user might have to complete email verification or something along those lines.

Related