I try to implement .onCreate
firebase cloud function like in Firebase cloud functions codeLab (https://codelabs.developers.google.com/codelabs/firebase-cloud-functions/#7)
exports.addWelcomeMessages = functions.auth.user().onCreate(event => {
const user = event.data;
console.log('user: %j', user);
const fullName = user.displayName;
return admin.database().ref('messages').push({
name: 'Firebase Bot',
text: `${fullName} signed in for the first time! Welcome!`
});
});
In my client iOS application I use email authentication flow via FirebaseUI, that requires user to enter his email, name and password to sign up. After user signed up, .onCreate
trigger in cloud functions fires, but user
structure does not contain displayName
data:
user: {"email":"[email protected]","metadata":{"createdAt":"2017-04-05T05:30:05.000Z","lastSignedInAt":"2017-04-05T05:30:05.000Z"},"uid":"wpIPNvf2suQdMumsEyXA5lQatt23"}
Notice: displayName
property in FIRUser
instance of current user in iOS app is filled correctly just after sign up process.
My assume that it is some kind of a bug in FirebaseUI that firstly creates an empty user with email, fires .onCreate
trigger and only after this fills displayName
property. Is it?
If not, what can be the cause of it?
This answer is not the proper method that the Firebase developers intended, but seeing as the code in the documentation does not work, since the users displayName property is not retrieved when an account is first created, I've come up with a simple workaround.
This code just uses the admin Node.js SDK found here: (https://firebase.google.com/docs/auth/admin/manage-users)
Here's the code:
const admin = require('firebase-admin'); // This is the required SDK
admin.initializeApp(functions.config().firebase); // SDK initialization is required
exports.addWelcomeMessages = functions.auth.user().onCreate(event => {
const user = event.data;
console.log('user: %j', user);
const uid = user.uid;
return 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());
const fullName = userRecord.displayName || 'Anonymous';
return admin.database().ref('messages').push({
name: 'Firebase Bot',
text: `${fullName} signed in for the first time! Welcome!`
});
})
.catch(function(error){
console.log("Error fetching user data:", error);
});
});
This code has to make an additional call to the database, but at least it solves the issue of the displayName not being available in the onCreate event data. It works in my own testing, but hopefully someone is able to solve the actual issue without a workaround.
Let me know if this doesn't work for you! Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With