0

I have a Flutter app in which admins can create accounts (using Firebase Authentication) for other users.

My logic is similar to the following:

UserCredential userCredential =
  await authService.instance.createUserWithEmailAndPassword(
  email: emailController.text,
  password: passwordController.text,
);

main.dart:

MaterialApp(
      home: StreamBuilder<User>(
        stream: authentcationService.authStateChanges,
        builder: (context, snapshot) {
          // Build the app
          // ...
        },
       )
)

However I noticed that this is triggering an auth state change in the stream above: calling createUserWithEmailAndPassword is logging out the current user and logging in the newly-created user, rather than simply creating a new user in Firebase Authentication. Can anyone advise?

user2181948
  • 1,646
  • 3
  • 33
  • 60

2 Answers2

1

I have seen a lot of discussion regarding this issue. I have found a lot of complex and hard explainations and answers.

But, to be honest, this is the most minimal and best way of performing an account creation from an authenticated account with keeping the new user logged out and not replacing the current user.

FirebaseApp tempApp = await Firebase.initializeApp(name: "flutter", options: Firebase.app().options);

UserCredential newUser = await FirebaseAuth.instanceFor(app: tempApp).createUserWithEmailAndPassword(email: email0, password: password0);

burnsi
  • 6,194
  • 13
  • 17
  • 27
Uraam Asif
  • 67
  • 7
0

When you create a user it automatically signs them in at the same time in my experience, regardless of sign up method. Even if you log out right after, the logged in user will still change.

Maybe you can implement a cloud function to create a user?(if this is possible?) Or you can save the correct/admin username password and automatically log out of the newly created account and log back into the admin account upon creation?

Example: (start logged in as admin who creates accounts)(pseudocode)

_createNewUserAsAdmin(email, password){
 var adminPass = SharedPreferences.adminPass;
 var adminEmail = SharedPreferences.adminEmail;

_auth.logout();

 var newUser= _auth.createUser(email, password);
 if(newUser == null){} //error creating user (user object is null), handle error and log back into admin
 else{
  _auth.logout()(
  _auth.signIn(adminEmail, adminPass);
 }
}

You’ll likely have to change your stream/auth app wrapper to handle this activity though.

Edit: This answer has a more in-depth solution: https://stackoverflow.com/a/38013551/13714686

Personally, I’d investigate creating the new user via a Firebase cloud function, it seems the simplest for you setup. Firebase also has the option to create users from files which you could look into more if you want your admins to bulk add users (although, I think this feature is for command line tools)

August Kimo
  • 1,503
  • 8
  • 17