Firebase 踢出当前用户

Firebase kicks out current user

所以我遇到了这个问题,每次我添加一个新用户帐户时,它都会踢出已经登录的当前用户。我读了 firebase api 并说“如果创建了新帐户,用户会自动登录 但他们从未说过要避免这种情况。

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

我是管理员,我正在向我的站点添加帐户。如果我可以添加一个帐户而无需注销并登录到新帐户,我会很高兴。我有什么办法可以避免这种情况吗?

更新 20161108 - 下面是原始答案

Firebase 刚刚发布了它的 firebase-admin SDK,它允许服务器端代码用于这个和其他常见的管理用例。阅读 installation instructions and then dive into the documentation on creating users.

原回答

这目前是不可能的。创建电子邮件+密码用户会自动让新用户登录。

更新 20161110 - 下面是原始答案

此外,请查看 以了解不同的方法。

原回答

这实际上是可能的。

但不是直接的,方法是创建第二个 auth 引用并使用它来创建用户:

var config = {apiKey: "apiKey",
    authDomain: "projectId.firebaseapp.com",
    databaseURL: "https://databaseName.firebaseio.com"};
var secondaryApp = firebase.initializeApp(config, "Secondary");

secondaryApp.auth().createUserWithEmailAndPassword(em, pwd).then(function(firebaseUser) {
    console.log("User " + firebaseUser.uid + " created successfully!");
    //I don't know if the next statement is necessary 
    secondaryApp.auth().signOut();
});

如果您没有指定用于操作的 firebase 连接,它将默认使用第一个。

Source 多个应用引用。

编辑

对于新用户的实际创建,除了管理员之外,没有人或其他人在第二个 auth 引用上进行身份验证并不重要,因为要创建一个帐户,您只需要 auth 引用本身。

以下没有测试过但值得思考

您需要考虑的事情是将数据写入 firebase。通常的做法是用户可以 edit/update 他们自己的用户信息,因此当您使用第二个 auth 参考来编写时,这应该可以工作。但是,如果您拥有该用户的角色或权限,请确保您使用具有正确权限的 auth 引用来编写它。在这种情况下,主要授权是管理员,第二个授权是新创建的用户。

使用 Firebase iOS SDK:

在 Objective-C 中工作
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];
                          }];

Swift版本:

FIRApp.configure()

// Creating a second app to create user without logging in
FIRApp.configure(withName: "CreatingUsersApp", options: FIRApp.defaultApp()!.options)

if let secondaryApp = FIRApp(named: "CreatingUsersApp") {
    let secondaryAppAuth = FIRAuth(app: secondaryApp)
    secondaryAppAuth?.createUser(...)
}

这是 的 Swift 3 改编版:

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

如果您使用的是 Polymer 和 Firebase (polymerfire),请参阅此答案:

本质上,您创建了一个辅助 <firebase-app> 来处理新用户注册而不影响当前用户。

更新 Swift 4

我尝试了几个不同的选项来从一个帐户创建多个用户,但这是迄今为止最好和最简单的解决方案。

的原始回答

首先在 AppDelegate.swift 文件中配置 firebase

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()
    FirebaseApp.configure(name: "CreatingUsersApp", options: FirebaseApp.app()!.options)

    return true
}

将以下代码添加到您创建帐户的操作中。

            if let secondaryApp = FirebaseApp.app(name: "CreatingUsersApp") {
                let secondaryAppAuth = Auth.auth(app: secondaryApp)
                
                // Create user in secondary app.
                secondaryAppAuth.createUser(withEmail: email, password: password) { (user, error) in
                    if error != nil {
                        print(error!)
                    } else {
                        //Print created users email.
                        print(user!.email!)
                        
                        //Print current logged in users email.
                        print(Auth.auth().currentUser?.email ?? "default")
                        
                        try! secondaryAppAuth.signOut()
                        
                    }
                }
            }
        }

我刚刚创建了一个 Firebase 函数,该函数在创建 Firestore 文档时触发(具有对管理员用户只写的规则)。然后使用 admin.auth().createUser() 正确创建新用户。

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

您可以使用算法 functions.https.onCall()

exports.createUser= functions.https.onCall((data, context) => {
    const uid = context.auth.uid; // Authorize as you want
    // ... do the same logic as above
});

调用它。

const createUser = firebase.functions().httpsCallable('createUser');
createUser({userData: data}).then(result => {
    // success or error handling
});

Android 解决方案(Kotlin):

1.You 需要 FirebaseOptions BUILDER(!) 来设置 api 键、db url 等,不要忘记在最后调用 build()

2.Make 通过调用 FirebaseApp.initializeApp()

的辅助 auth 变量

3.Get FirebaseAuth 实例,通过传递您新创建的辅助身份验证,并执行您想要的任何操作(例如 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()

            }

        }

    }

您可以使用 firebase 功能添加用户。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const cors = require('cors')({
origin: true,
});
exports.AddUser = functions.https.onRequest(( req, res ) => {
// Grab the text parameter.

cors( req, res, ()  => {
    let email  = req.body.email;
    let passwd = req.body.passwd;
    let role   = req.body.role;
    const token = req.get('Authorization').split('Bearer ')[1];

    admin.auth().verifyIdToken(token)
    .then(
            (decoded) => { 
             // return res.status(200).send(  decoded )
             return creatUser(decoded);
            })
    .catch((err) => {
            return res.status(401).send(err) 
     });
       
    function creatUser(user){
      admin.auth().createUser({
          email: email,
          emailVerified: false,
          password: passwd,
          disabled: false
        })
        .then((result) => {
          console.log('result',result);
           return res.status(200).send(result);
        }).catch((error) => {
           console.log(error.message);
           return res.status(400).send(error.message);
       })
     }

   }); 
 });

  CreateUser(){
//console.log('Create User')
this.submitted = true;
if (this.myGroup.invalid) {
  return;
}


let Email    = this.myGroup.value.Email;
let Passwd   = this.myGroup.value.Passwd;
let Role     = 'myrole';
let TechNum  = this.myGroup.value.TechNum;
let user     = JSON.parse(localStorage.getItem('user'));
let role     = user.role;
let AdminUid = user.uid;
let authToken = user.stsTokenManager.accessToken;
let httpHeaders = new HttpHeaders().set('Authorization', 'Bearer ' + authToken);
let options = { headers: httpHeaders };
let params  = { email:Email,passwd:Passwd,role:Role };

this.httpClient.post('https://us-central1-myproject.cloudfunctions.net/AddUser', params, options)
.subscribe( val => { 
           //console.log('Response from cloud function', val ); 
           let createdUser:any = val;
           //console.log(createdUser.uid);
           const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${createdUser.uid}`);
                 const userUpdate = {
                             uid: createdUser.uid,
                             email: createdUser.email,
                             displayName: null,
                             photoURL: null,
                             emailVerified: createdUser.emailVerified,
                             role: Role,
                             TechNum:TechNum,
                             AccountAccess:this.AccountAccess,
                             UserStatus:'open',
                             OwnerUid:AdminUid,
                             OwnerUidRole:role,
                             RootAccountAccess:this.RootAccountAccess
                      }
                       userRef.set(userUpdate, {
                             merge: false
                       });
                          this.toastr.success('Success, user add','Success');
                          this.myGroup.reset();
                          this.submitted = false;
                       },
                       err => { 
                         console.log('HTTP Error', err.error)
                         this.toastr.error(err.error,'Error')
                       },
                       () => console.log('HTTP request completed.')
    );

}

Swift 5:简单的解决方案

首先将当前用户存储在一个名为 originalUser 的变量中

let originalUser = Auth.auth().currentUser

然后,在创建新用户的完成句柄中,使用updateCurrentUser方法恢复原用户

Auth.auth().updateCurrentUser(originalUser, completion: nil)

这是一个使用网络 SDK 的简单解决方案。

  1. 创建云函数(https://firebase.google.com/docs/functions)
import admin from 'firebase-admin';
import * as functions from 'firebase-functions';

const createUser = functions.https.onCall((data) => {
  return admin.auth().createUser(data)
    .catch((error) => {
      throw new functions.https.HttpsError('internal', error.message)
    });
});

export default createUser;
  1. 从您的应用程序调用此函数
import firebase from 'firebase/app';

const createUser = firebase.functions().httpsCallable('createUser');

createUser({ email, password })
  .then(console.log)
  .catch(console.error);
  1. 可选地,您可以使用返回的 uid 设置用户文档信息。
createUser({ email, password })
  .then(({ data: user }) => {
    return database
      .collection('users')
      .doc(user.uid)
      .set({
        firstname,
        lastname,
        created: new Date(),
      });
  })
  .then(console.log)
  .catch(console.error);

在网络上,这是由于您在注册上下文之外调用 createUserWithEmailAndPassword 时出现意外行为;例如通过创建新用户帐户邀请新用户使用您的应用。

看起来,createUserWithEmailAndPassword 方法触发了一个新的刷新令牌,并且用户 cookie 也被更新了。 (此 side-effect 未记录)

这是 Web SDK 的解决方法: 创建新用户后;

firebase.auth().updateCurrentUser (loggedInUser.current)

前提是您事先用原始用户启动了 loggedInUser。

嘿,我有类似的问题,试图通过管理员创建用户,因为没有登录就无法注册用户,我创建了一个解决方法,在下面添加了步骤

  1. 不是注册,而是在 firebase 实时数据库中创建一个以电子邮件作为密钥的节点(firebase 不允许电子邮件作为密钥,所以我创建了一个函数来从电子邮件生成密钥,反之亦然,我将在下面附加函数)
  2. 在保存用户的同时保存一个初始密码字段(甚至可以用 bcrypt 或其他东西对其进行哈希处理,如果你愿意,虽然它只会被使用一次)
  3. 现在,一旦用户尝试登录,请检查数据库中是否存在具有该电子邮件的任何节点(从电子邮件生成密钥),如果存在,则匹配提供的密码。
  4. 如果密码匹配,则删除节点并使用提供的凭据执行 authSignUpWithEmailandPassword。
  5. 用户注册成功
//Sign In
firebaseDB.child("users").once("value", (snapshot) => {
     const users = snapshot.val();
     const userKey = emailToKey(data.email);
     if (Object.keys(users).find((key) => key === userKey)) {
       setError("user already exist");
       setTimeout(() => {
         setError(false);
       }, 2000);
       setLoading(false);
     } else {
       firebaseDB
         .child(`users`)
         .child(userKey)
         .set({ email: data.email, initPassword: data.password })
         .then(() => setLoading(false))
         .catch(() => {
           setLoading(false);
           setError("Error in creating user please try again");
           setTimeout(() => {
             setError(false);
           }, 2000);
         });
     }
   });

//Sign Up 
signUp = (data, setLoading, setError) => {
 auth
   .createUserWithEmailAndPassword(data.email, data.password)
   .then((res) => {
     const userDetails = {
       email: res.user.email,
       id: res.user.uid,
     };
     const key = emailToKey(data.email);
     app
       .database()
       .ref(`users/${key}`)
       .remove()
       .then(() => {
         firebaseDB.child("users").child(res.user.uid).set(userDetails);
         setLoading(false);
       })
       .catch(() => {
         setLoading(false);
         setError("error while registering try again");
         setTimeout(() => setError(false), 4000);
       });
   })
   .catch((err) => {
     setLoading(false);
     setError(err.message);
     setTimeout(() => setError(false), 4000);
   });
};

//Function to create a valid firebase key from email and vice versa
const emailToKey = (email) => {
 //firebase do not allow ".", "#", "$", "[", or "]"
 let key = email;
 key = key.replace(".", ",0,");
 key = key.replace("#", ",1,");
 key = key.replace("$", ",2,");
 key = key.replace("[", ",3,");
 key = key.replace("]", ",4,");

 return key;
};

const keyToEmail = (key) => {
 let email = key;
 email = email.replace(",0,", ".");
 email = email.replace(",1,", "#");
 email = email.replace(",2,", "$");
 email = email.replace(",3,", "[");
 email = email.replace(",4,", "]");

 return email;
};

如果您想在前端执行此操作,请创建第二个身份验证引用,使用它来创建其他用户并注销并删除该引用。如果您这样做,您在创建新用户时不会退出,也不会收到默认 firebase 应用程序已存在的错误。

   const createOtherUser =()=>{
            var config = {
                //your firebase config
            };
            let secondaryApp = firebase.initializeApp(config, "secondary");

            secondaryApp.auth().createUserWithEmailAndPassword(email, password).then((userCredential) => {
                console.log(userCredential.user.uid);
            }).then(secondaryApp.auth().signOut()
            )
            .then(secondaryApp.delete()
            )


        }
        

对于 Android,我建议采用更简单的方法,无需仅使用 FirebaseOptions 手动提供 api 密钥、应用程序 ID...等默认实例。

val firebaseDefaultApp = Firebase.auth.app
val signUpAppName = firebaseDefaultApp.name + "_signUp"

val signUpApp = try {
    FirebaseApp.initializeApp(
        context,
        firebaseDefaultApp.options,
        signUpAppName
    )
} catch (e: IllegalStateException) {
    // IllegalStateException is throw if an app with the same name has already been initialized.
    FirebaseApp.getInstance(signUpAppName)
}

// Here is the instance you can use to sign up without triggering auth state on the default Firebase.auth
val signUpFirebaseAuth = Firebase.auth(signUpApp)

如何使用?

signUpFirebaseAuth
            .createUserWithEmailAndPassword(email, password)
            .addOnSuccessListener {
                // Optional, you can send verification email here if you need

                // As soon as the sign up with sign in is over, we can sign out the current user
                firebaseAuthSignUp.signOut()
            }
            .addOnFailureListener {
                // Log
            }

我对这个问题的解决方案是将用户 Name/Email 和密码存储在静态 class 中,然后添加一个新用户注销新用户并立即以管理员用户身份登录( id 传给你保存)。对我来说就像一个魅力 :D

更新 19.05.2022 - 使用@angular/fire(最新可用 = v.7.3.0)

如果您不直接在您的应用中使用 firebase,而是使用例如@angular/fire 仅用于身份验证目的,您可以使用与@angular/fire 库相同的方法,如下所示:

import { Auth, getAuth, createUserWithEmailAndPassword } from '@angular/fire/auth';
import { deleteApp, initializeApp } from '@angular/fire/app';
import { firebaseConfiguration } from '../config/app.config';   // <-- Your project's configuration here.


const tempApp = initializeApp(firebaseConfiguration, "tempApp");
const tempAppAuth = getAuth(tempApp);
await createUserWithEmailAndPassword(tempAppAuth, email, password)
.then(async (newUser) => {
    resolve( () ==>  {
        // Do something, e.g. add user info to database
    });
})
.catch(error => reject(error))
.finally( () => {
    tempAppAuth.signOut()
    .then( () => deleteApp(tempApp)); 
});