Firebase kicks out current user

2018-12-31 06:28发布

So I have this issue where every time I add a new user account, it kicks out the current user that is already signed in. I read the firebase api and it said that "If the new account was created, the user is signed in automatically" But they never said anything else about avoiding that.

      //ADD EMPLOYEES
      addEmployees: function(formData){
        firebase.auth().createUserWithEmailAndPassword(formData.email, formData.password).then(function(data){
          console.log(data);
        });
      },

I'm the admin and I'm adding accounts into my site. I would like it if I can add an account without being signed out and signed into the new account. Any way i can avoid this?

11条回答
素衣白纱
2楼-- · 2018-12-31 07:12

I just created a Firebase Function that triggers when a Firestore document is Created (with rules write-only to admin user). Then use admin.auth().createUser() to create the new user properly.

export const createUser = functions.firestore
.document('newUsers/{userId}')
.onCreate(async (snap, context) => {
    const userId = context.params.userId;
    const newUser = await admin.auth().createUser({
        disabled: false,
        displayName: snap.get('displayName'),
        email: snap.get('email'),
        password: snap.get('password'),
        phoneNumber: snap.get('phoneNumber')
    });
    // You can also store the new user in another collection with extra fields
    await admin.firestore().collection('users').doc(newUser.uid).set({
        uid: newUser.uid,
        email: newUser.email,
        name: newUser.displayName,
        phoneNumber: newUser.phoneNumber,
        otherfield: snap.get('otherfield'),
        anotherfield: snap.get('anotherfield')
    });
    // Delete the temp document
    return admin.firestore().collection('newUsers').doc(userId).delete();
});
查看更多
骚的不知所云
3楼-- · 2018-12-31 07:14

Here is a Swift 3 adaptaion of Jcabrera's answer :

let bundle = Bundle.main
        let path = bundle.path(forResource: "GoogleService-Info", ofType: "plist")!
        let options = FIROptions.init(contentsOfFile: path)
        FIRApp.configure(withName: "Secondary", options: options!)
        let secondary_app = FIRApp.init(named: "Secondary")
        let second_auth = FIRAuth(app : secondary_app!)
        second_auth?.createUser(withEmail: self.username.text!, password: self.password.text!)
        {
            (user,error) in
            print(user!.email!)
            print(FIRAuth.auth()?.currentUser?.email ?? "default")
        }
查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 07:15

Android solution (Kotlin):

  1. You need FirebaseOptions BUILDER(!) for setting api key, db url, etc., and don't forget to call build() at the end
  2. Make a secondary auth variable by calling FirebaseApp.initializeApp()
  3. Get instance of FirebaseAuth by passing your newly created secondary auth, and do whatever you want (e.g. createUser)

    // 1. you can find these in your project settings under general tab
    val firebaseOptionsBuilder = FirebaseOptions.Builder()
    firebaseOptionsBuilder.setApiKey("YOUR_API_KEY")
    firebaseOptionsBuilder.setDatabaseUrl("YOUR_DATABASE_URL")
    firebaseOptionsBuilder.setProjectId("YOUR_PROJECT_ID")
    firebaseOptionsBuilder.setApplicationId("YOUR_APPLICATION_ID") //not sure if this one is needed
    val firebaseOptions = firebaseOptionsBuilder.build()
    
    // indeterminate progress dialog *ANKO*
    val progressDialog = indeterminateProgressDialog(resources.getString(R.string.progressDialog_message_registering))
    progressDialog.show()
    
    // 2. second auth created by passing the context, firebase options and a string for secondary db name
    val newAuth = FirebaseApp.initializeApp(this@ListActivity, firebaseOptions, Constants.secondary_db_auth)
    // 3. calling the create method on our newly created auth, passed in getInstance
    FirebaseAuth.getInstance(newAuth).createUserWithEmailAndPassword(email!!, password!!)
            .addOnCompleteListener { it ->
    
                if (it.isSuccessful) {
    
                    // 'it' is a Task<AuthResult>, so we can get our newly created user from result
                    val newUser = it.result.user
    
                    // store wanted values on your user model, e.g. email, name, phonenumber, etc.
                    val user = User()
                    user.email = email
                    user.name = name
                    user.created = Date().time
                    user.active = true
                    user.phone = phone
    
                    // set user model on /db_root/users/uid_of_created_user/, or wherever you want depending on your structure
                    FirebaseDatabase.getInstance().reference.child(Constants.db_users).child(newUser.uid).setValue(user)
    
                    // send newly created user email verification link
                    newUser.sendEmailVerification()
    
                    progressDialog.dismiss()
    
                    // sign him out
                    FirebaseAuth.getInstance(newAuth).signOut()
                    // DELETE SECONDARY AUTH! thanks, Jimmy :D
                    newAuth.delete()
    
                } else {
    
                    progressDialog.dismiss()
    
                    try {
    
                        throw it.exception!!
    
                        // catch exception for already existing user (e-mail)
                    } catch (e: FirebaseAuthUserCollisionException) {
    
                        alert(resources.getString(R.string.exception_FirebaseAuthUserCollision), resources.getString(R.string.alertDialog_title_error)) {
    
                            okButton {
    
                                isCancelable = false
    
                            }
    
                        }.show()
    
                    }
    
                }
    
            }
    
查看更多
时光乱了年华
5楼-- · 2018-12-31 07:16

I got André's very clever workaround working in Objective-C using the Firebase iOS SDK:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"];
FIROptions *secondaryAppOptions = [[FIROptions alloc] initWithContentsOfFile:plistPath];
[FIRApp configureWithName:@"Secondary" options:secondaryAppOptions];
FIRApp *secondaryApp = [FIRApp appNamed:@"Secondary"];
FIRAuth *secondaryAppAuth = [FIRAuth authWithApp:secondaryApp];

[secondaryAppAuth createUserWithEmail:user.email
                             password:user.password
                           completion:^(FIRUser * _Nullable user, NSError * _Nullable error) {
                                [secondaryAppAuth signOut:nil];
                          }];
查看更多
伤终究还是伤i
6楼-- · 2018-12-31 07:23

Update 20161108 - original answer below

Firebase just released its firebase-admin SDK, which allows server-side code for this and other common administrative use-cases. Read the installation instructions and then dive into the documentation on creating users.

original answer

This is currently not possible. Creating an Email+Password user automatically signs that new user in.

查看更多
登录 后发表回答