0
votes

I am using angular for front-end and firebase for back-end. I created a form in angular to take in some fields like first name, last name, email, password, mobile no., address etc.

When I submit the form, I want to do two things --
1. Create a user account with email and password.
2. Add a document in my users collection in firestore with the fields firstname, lastname, mobile no., address etc.
I don't want to do these 2 things on client side.

So, I created a cloud function in firebase to do the above two things like so --

export const register = functions.https.onCall((data, context) => {
    const firestore = admin.firestore();
    const auth = admin.auth();

    return auth.createUser({
        email: data.email,
        password: data.password
    }).then(user => {
        let dbData = {};

        // Assign all fields to dbData except 'email' and 'password' because I don't want to store those fields in the database
        Object.keys(data).forEach(el => { if (el != 'email' && el != 'password') dbData[el] = data[el];});

        return firestore.collection('users').doc(user.uid)
        .set(dbData)
        .then(() => {
            return 'success';
        }, error => {
            throw new functions.https.HttpsError('unknown', 'Unknown error.');
        });
    }, error => {
        throw new functions.https.HttpsError('unknown', 'Unknown error.');
    });
});

I invoke the cloud function in angular with angularfire2 like this --

const registerFunction = this.afFunctions.functions.httpsCallable('register');
registerFunction(data)
.then(() => {
    // Account created successfully
}),
error => {
    // Error occured
});

The account gets created successfully. But the problem is the browser (client app) is not logged in to the account just created. I want the user to be logged in when he/she registers.

So my question is how to get the user signed in on client by calling https callable function?

1

1 Answers

0
votes

You do want to do this client side. You create a form, take the users email address and password, then call .createUserWithEmailAndPassword. The browser will be running the Firebase SDK which has an .onAuthStateChanged listener that will switch from null to currentUser object.

It's recommended to use validate the user own the email first though by firing a validation link first.