创建新用户后,Firebase身份验证状态更改

时间:2019-02-01 20:59:44

标签: javascript firebase firebase-authentication

使用电子邮件和密码创建新用户时,验证状态会更改。 我实现了firebase.auth().onAuthStateChanged(),可以观察我的应用程序中的登录状态。但是它具有用于创建复制问题的新用户的工具。用firebase.auth().createUserWithEmailAndPassword()创建新用户后,可观察对象将返回新用户,这会导致我的应用注销。

这正常吗?如何在不更改身份验证状态的情况下通过我的应用创建新用户?

See the stackblitz example

1 个答案:

答案 0 :(得分:1)

在使用firebase.auth().createUserWithEmailAndPassword()创建用户时,它将自动注销当前用户并登录到新创建的用户。为避免这种情况,您必须使用admin sdk创建新用户。

这是示例代码:

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);
    }

});
相关问题