创建新用户后,Firebase身份验证状态更改 [英] Firebase Auth state changes after creating new user

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

问题描述

使用电子邮件和密码创建新用户时,验证状态会更改. 我实现了firebase.auth().onAuthStateChanged(),可以观察我的应用程序中的登录状态.但是它具有用于创建复制问题的新用户的工具.使用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天全站免登陆