Firebase Auth state changes after creating new user

余生长醉 提交于 2020-01-23 17:07:41

问题


Auth state changes when a new user is created with email and password. I implement firebase.auth().onAuthStateChanged() observable to watch login state in my app. But it have tool for creating new users that reproduces de issue. After creating new user withfirebase.auth().createUserWithEmailAndPassword() the observable returns the new user, wich causes my app log out.

Is this normal? How can I create new users from my app without changing auth state?

See the stackblitz example


回答1:


while creating the user using firebase.auth().createUserWithEmailAndPassword() it will automatically logged out the current user and will logged into the newly created user.To avoid this you have to create the new user using admin sdk.

here is the sample code:

exports.createUser = functions.firestore
.document('user/{userId}')
.onCreate(async (snap, context) => {
    try {
        const userId = snap.id;
        const batch = admin.firestore().batch();
        const newUser = await admin.auth().createUser({
            disabled: false,
            displayName: snap.get('name'),
            email: snap.get('email'),
            password: snap.get('password')
        });

        const ref1 = await 
        admin.firestore().collection('user').doc(newUser.uid);
            await batch.set(ref1, {
            id: newUser.uid,
            email: newUser.email,
            name: newUser.displayName,
            createdAt: admin.firestore.FieldValue.serverTimestamp()
        });
        const ref3 = await admin.firestore().collection('user').doc(userId);
        await batch.delete(ref3);
        return await batch.commit();
    }
    catch (error) {
        console.error(error);
    }

});


来源:https://stackoverflow.com/questions/54487092/firebase-auth-state-changes-after-creating-new-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!