创建新用户后,Firebase身份验证状态会发生变化 [英] Firebase Auth state changes after creatng new user

查看:119
本文介绍了创建新用户后,Firebase身份验证状态会发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用电子邮件和密码创建新用户时,身份验证状态会更改。
我实现了 firebase.auth()。onAuthStateChanged() observable来监视我的应用程序中的登录状态。但它有创建新用户的工具,可以重现问题。使用 firebase.auth()。createUserWithEmailAndPassword()创建新用户后,observable返回新用户,导致我的应用程序注销。

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?

查看stackblitz示例

推荐答案

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

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.

这里是示例代码:

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

});

这篇关于创建新用户后,Firebase身份验证状态会发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆