firebase驱逐当前用户

jqjz2hbq  于 2021-07-03  发布在  Java
关注(0)|答案(14)|浏览(278)

所以我有一个问题,每次我添加一个新的用户帐户,它踢出当前用户已经登录。我读过firebase api,上面说“如果创建了新帐户,用户将自动登录”,但他们从来没有说过要避免这种情况。

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

我是管理员,我正在添加帐户到我的网站。我想它,如果我可以添加一个帐户没有被注销,并签署到新的帐户。有什么办法可以避免吗?

yws3nbqq

yws3nbqq1#

我刚刚创建了一个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
});
kqlmhetl

kqlmhetl2#

如果您使用的是聚合物和火基(polymerfire),请参阅以下答案:https://stackoverflow.com/a/46698801/1821603
从本质上说,您创建了一个辅助 <firebase-app> 在不影响当前用户的情况下处理新用户注册。

webghufk

webghufk3#

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(...)
}
uubf1zoe

uubf1zoe4#

在web上,这是由于在注册上下文之外调用createuserwithemailandpassword时出现意外行为所致;e、 g.通过创建新用户帐户邀请新用户加入你的应用程序。
似乎,createuserwithemailandpassword方法会触发一个新的刷新令牌,用户cookie也会更新(这种副作用没有记录)
以下是websdk的解决方法:在创建新用户之后;

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

前提是您事先与原始用户启动loggedinuser。

hm2xizp9

hm2xizp95#

更新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连接,则默认情况下,它将使用第一个firebase连接。
多个应用程序引用的源。
编辑
对于新用户的实际创建,除了管理员之外没有人或其他人在第二个auth引用上进行身份验证并不重要,因为创建帐户所需的只是auth引用本身。
以下内容尚未测试,但值得思考
您必须考虑的是将数据写入firebase。通常的做法是,用户可以编辑/更新他们自己的用户信息,所以当您使用第二个auth引用进行编写时,这应该是可行的。但是,如果您对该用户具有类似角色或权限的权限,请确保使用具有正确权限的auth引用来编写。在本例中,主身份验证是admin,第二身份验证是新创建的用户。

vbopmzt1

vbopmzt16#

以下是对jcabrera答案的快速修改:

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

nzrxty8p7#

更新20161108-原始答案如下

firebase刚刚发布了firebase管理sdk,它允许服务器端代码用于这个和其他常见的管理用例。阅读安装说明,然后深入阅读有关创建用户的文档。
原始答案
目前这是不可能的。创建一个电子邮件+密码用户会自动将该新用户登录。

s1ag04yj

s1ag04yj8#

我也面临同样的问题,我用这种方式解决了它:
当用户登录时,我将电子邮件和密码保存在共享首选项中。在创建用户之后,我用之前保存的电子邮件和密码再次登录用户。

String currentEmail = MyApp.getSharedPreferences().getEmail();
    String currentPass = MyApp.getSharedPreferences().getPass();

    FirebaseAuth auth = FirebaseAuth.getInstance();
    auth.createUserWithEmailAndPassword(email, pass)
            .addOnCompleteListener(AddStudent.this, new OnCompleteListener<AuthResult>() {

                @Override
                public void onComplete(@NonNull final Task<AuthResult> task) {

                    if (task.isSuccessful()) {
                        String currentEmail = MyApp.getSharedPreferences().getEmail();
                        String currentPass = MyApp.getSharedPreferences().getPass();

                        //Sign in again
                        auth.signInWithEmailAndPassword(currentEmail, currentPass)
                                .addOnCompleteListener(AddStudent.this, new OnCompleteListener<AuthResult>() {
                                    @Override
                                    public void onComplete(@NonNull Task<AuthResult> task) {
                                        if (!task.isSuccessful()) {
                                            Log.e("RELOGIN", "FAILED");
                                        } else {
                                            Log.e("RELOGIN", "SUCCESS");
                                        }
                                    }
                                });

                        finish();
                    }
                }
    });
vhipe2zx

vhipe2zx9#

swift 5:简单解决方案

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

let originalUser = Auth.auth().currentUser

然后,在创建新用户的完成处理程序中,使用updatecurrentuser方法还原原始用户

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

wnavrhmk10#

我找到安德烈了é'在objective-c中使用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];
                          }];
3zwtqj6y

3zwtqj6y11#

android解决方案(kotlin):
1.您需要firebaseoptions生成器(!)用于设置api键、db url等,不要忘记在最后调用build()
2.通过调用firebaseapp.initializeapp()生成辅助身份验证变量
3.通过传递新创建的二级身份验证来获取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()

            }

        }

    }
fcipmucu

fcipmucu12#

您可以使用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);
       })
     }

   }); 
 });
svmlkihl

svmlkihl13#

下面是一个使用websdk的简单解决方案。
创建云函数(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;

从应用程序调用此函数

import firebase from 'firebase/app';

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

createUser({ email, password })
  .then(console.log)
  .catch(console.error);

或者,可以使用返回的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);
zqdjd7g9

zqdjd7g914#

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

                    }
                }
            }
        }

相关问题