【问题标题】:creating user is changing the current user创建用户正在更改当前用户
【发布时间】:2021-04-28 07:43:38
【问题描述】:

我有以下代码可以使用 Flutter 登录 Firebase。这很好用。

FirebaseAuth.instance.signInWithEmailAndPassword(email: myemail, password: mypassword);

身份验证成功后,我正在使用以下代码创建 nw 用户。

UserCredential userCredentials = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: myemail, password: mypassword);

但是,随着方法,当前用户会发生变化。我想在不更改当前用户的情况下创建用户。这可能吗?

【问题讨论】:

  • 如果第一条语句工作正常并且用户登录,那么为什么要创建具有相同凭据的新用户?
  • 实际上,我正在尝试使用管理面板在登录后创建用户。描述中的代码可以吗?

标签: flutter


【解决方案1】:

我找到了一种解决方案,它对我有用

在主 dart 文件中像这样初始化应用程序

void main() async{
await Firebase.initializeApp();
  runApp(MyApp());
}

创建一个简单/管理员用户

FirebaseAuth.instance.signInWithEmailAndPassword(email: myemail, password: mypassword);

添加另一个用户

FirebaseApp app = await Firebase.initializeApp(
        name: 'secondary', options: Firebase.app().options);
await FirebaseAuth.instanceFor(app: app)
        .createUserWithEmailAndPassword(
            email: _email, password: _password);

app.delete();

【讨论】:

    【解决方案2】:

    这是 Flutter: Firebase Authentication Create User Without Automatically Logging In 的副本,但我无法标记这个问题,因为它有一个开放的赏金。

    您需要创建 FirebaseApp 的第二个实例并使用该实例创建新用户:

    static Future<UserCredential> register(String email, String password) async {
        FirebaseApp app = await Firebase.initializeApp(
            name: 'Secondary', options: Firebase.app().options);
        try {
            UserCredential userCredential = await FirebaseAuth.instanceFor(app: app)
            .createUserWithEmailAndPassword(email: email, password: password);
        }
        on FirebaseAuthException catch (e) {
          // Do something with exception. This try/catch is here to make sure 
          // that even if the user creation fails, app.delete() runs, if is not, 
          // next time Firebase.initializeApp() will fail as the previous one was
          // not deleted.
        }
        
        await app.delete();
        return Future.sync(() => userCredential);
    }
    

    【讨论】:

      【解决方案3】:

      您尝试做的事情不安全(生成其他人的密码) 从这个意义上说,您是正确的,作为管理员,您无法为另一封电子邮件创建密码。

      你想做的是sendSignInLinkTOEmail

      这与注册 GSuit 和其他流行服务的程序相同。

      如果您真的需要设置用户,则必须使用单独的身份验证模块(应该很容易编写自己的)而不是 firebase,然后在用户注册时将其链接在一起。这是一种 hacky 方式,我不推荐它。

      【讨论】:

        猜你喜欢
        • 2017-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多