Todor Todorov
Todor Todorov

Reputation: 109

Cloud Functions for Firebase auth.user API has empty displayName property

I have an Android app using Firebase with database, authentication and cloud functions modules. When a user creates a profile through the app and sets a user full name, the value of

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // user signed in
    String displayName = user.getDisplayName();
    // do whatever with displayName...
} else {
    // ....
}

is pretty much as expected - whatever the user put in.

I also have a cloud function, which creates a database record for the new user:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.createUserRecord = functions.auth.user().onCreate(function(event) {
    const user = event.data;
    const userName = user.displayName || 'Anonymous';
    const userSignedUp = (new Date()).toJSON();
    console.log('A new user signed up: ', user.uid, userName, userSignedUp);
    return admin.database().ref('users').push({
        name: `${userName}`,
        email: `${user.email}`,
        ref: `${user.uid}`,
        signup: `${userSignedUp}`
    });
});

This works mostly OK, except that both the log entry, and the resulting record in the database list Anonymous as the name value.

Can anyone please tell me where I am going wrong with this? Thanks.

Best regards,

~Todor

UPDATE:

Forgot to mention, the user is created with the email/password provider.

Upvotes: 0

Views: 1524

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38309

In FirebaseUI, creation of a user via email/password is done in two steps: the user is created using the address and password, then the user profile is update with the entered username. This can be seen in the FirebaseUI RegisterEmailFragment.

At this time, Cloud Functions offers only a trigger for user creation, the one you are using, functions.auth.user().onCreate(). There is no trigger for user profile update. Your trigger fires when the user is created. The event data contains the user profile as it exists at that moment, before it has been updated with the user name.

You will need to use some other means to obtain the user name. One option is to use a database event to trigger a function that would retrieve the user data after the profile is updated:

admin.auth().getUser(uid)
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log("Successfully fetched user data:", userRecord.toJSON());
  })
  .catch(function(error) {
    console.log("Error fetching user data:", error);
  });

Upvotes: 9

Related Questions