I did this a little differently. I have a cloud function that creates the user account calling createUser() which receives in all the information I want to add to the account both in Authentication and in Firestore. I throw HttpsError when accounts exists or there is a DB issue. When I return back to the front end, I then call signInWithEmailAndPassword to log user in on front end. This allows me to easily populate the account with data I want while keeping the method more secured in a function. I fully understand there are many ways to accomplish, just sharing what I did. Also note this code is NOT cleaned up nor are all errors properly caught yet. I am sure it could be greatly improved.
Firebase function:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
// http callable function createUser
exports.createUser = functions.https.onCall(async (data, context) => {
const firstName = data.firstName;
const lastName = data.lastName;
const email = data.email;
const password = data.password;
await admin.auth().createUser({
email: email,
password: password,
displayName: firstName + " " + lastName,
disabled: false,
customClaims: {roleId: 1},
}).then(function(userRecord) {
db.collection("users").doc(userRecord.uid).set({
firstname: firstName,
lastname: lastName,
}).catch((err) => {
console.log("Failure to save user in DB. Error was " + err.message);
throw new functions.https.HttpsError('already-exists','Unable to create account. Contact support.');
});
}).catch(function(error) {
console.log("Error creating new user in Authentication. Error was ", error.message);
throw new functions.https.HttpsError('already-exists','Email account already exists');
});
return "success";
});
My front end JavaScript
const registerForm = document.querySelector('.register');
registerForm.addEventListener('submit', (e) => {
e.preventDefault();
const password = registerForm.password.value;
const confirm = registerForm.confirm.value;
if (password == confirm){
const firstName = registerForm.first_name.value;
const lastName = registerForm.last_name.value;
const email = registerForm.email.value;
const createUser = functions.httpsCallable('createUser');
const data = {
firstName: firstName,
lastName: lastName,
email: email,
password: password
};
createUser(data).then(response => {
// Now lets try to log the user in
firebase.auth().signInWithEmailAndPassword(email,password).then(userRecord => {
console.log("successfully logged in " + email);
}).catch((err) => {
console.log("Failure to log in user. Error was " + err.message);
});
// Do something here to manage UI
}).catch((e)=> {
console.log(e.message);
// Handle Errors in UI
});
} else {
// Handle Errors in UI
};
});