Javascript Firebase 踢出当前用户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37517208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Firebase kicks out current user
提问by Victor Le
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.
所以我有这个问题,每次添加新用户帐户时,它都会踢出已经登录的当前用户。我阅读了 firebase api,它说“如果创建了新帐户,用户将自动登录“但他们从来没有说过要避免这种情况。
//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?
我是管理员,我正在向我的网站添加帐户。如果我可以在不注销并登录新帐户的情况下添加帐户,我希望它。有什么办法可以避免这种情况吗?
回答by André Kool
Update 20161110 - original answer below
更新 20161110 - 下面的原始答案
Also, check out this answerfor a different approach.
另外,请查看此答案以了解不同的方法。
Original answer
原答案
This is actually possible.
这实际上是可能的。
But not directly, the way to do it is to create a second auth reference and use that to create users:
但不是直接的,这样做的方法是创建第二个身份验证引用并使用它来创建用户:
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();
});
If you don't specify which firebase connection you use for an operation it will use the first one by default.
如果您未指定用于操作的 Firebase 连接,它将默认使用第一个连接。
Sourcefor multiple app references.
多个应用程序引用的来源。
EDIT
编辑
For the actual creation of a new user, it doesn't matter that there is nobody or someone else than the admin, authenticated on the second auth reference because for creating an account all you need is the auth reference itself.
对于新用户的实际创建,除了管理员之外没有任何人或其他人都没有关系,在第二个身份验证引用上进行身份验证,因为创建帐户所需的只是身份验证引用本身。
The following hasn't been tested but it is something to think about
以下尚未经过测试,但值得考虑
The thing you do have to think about is writing data to firebase. Common practice is that users can edit/update their own user info so when you use the second auth reference for writing this should work. But if you have something like roles or permissions for that user make sure you write that with the auth reference that has the right permissions. In this case, the main auth is the admin and the second auth is the newly created user.
您必须考虑的是将数据写入 Firebase。常见的做法是用户可以编辑/更新他们自己的用户信息,因此当您使用第二个身份验证参考来编写时,这应该可以工作。但是,如果您拥有该用户的角色或权限之类的内容,请确保使用具有正确权限的 auth 引用编写这些内容。在这种情况下,主身份验证是管理员,第二身份验证是新创建的用户。
回答by Frank van Puffelen
Update 20161108 - original answer below
更新 20161108 - 下面的原始答案
Firebase just released its firebase-admin SDK, which allows server-side code for this and other common administrative use-cases. Read the installation instructionsand then dive into the documentation on creating users.
Firebase 刚刚发布了它的 firebase-admin SDK,它允许服务器端代码用于这个和其他常见的管理用例。阅读安装说明,然后深入了解有关创建用户的文档。
original answer
原答案
This is currently not possible. Creating an Email+Password user automatically signs that new user in.
这是目前不可能的。创建电子邮件+密码用户会自动让该新用户登录。
回答by Paulo Busato Favarato
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.
我刚刚创建了一个 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();
});
You can Algo use functions.https.onCall()
您可以使用算法使用 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
});
calling it.
调用它。
const createUser = firebase.functions().httpsCallable('createUser');
createUser({userData: data}).then(result => {
// success or error handling
});
回答by Jonathan Cabrera
I got André's very clever workaroundworking in Objective-C using the Firebase iOS SDK:
我使用 Firebase iOS SDK在 Objective-C 中得到了André 非常聪明的解决方法:
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];
}];
回答by B.Slade
Update for Swift 4
Swift 4 更新
I have tried a few different options to create multiple users from a single account, but this is by far the best and easiest solution.
我尝试了几种不同的选项来从单个帐户创建多个用户,但这是迄今为止最好和最简单的解决方案。
Original answer by Nico
Nico的原始答案
First Configure firebase in your AppDelegate.swift file
首先在 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
}
Add the following code to action where you are creating the accounts.
将以下代码添加到要创建帐户的操作中。
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()
}
}
}
}
回答by Юрий Лукашов
You can use firebase function for add users.
您可以使用 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);
})
}
});
});
回答by caesic
Swift 5: Simple Solution
Swift 5:简单的解决方案
First store the current user in a variable called originalUser
首先将当前用户存储在一个名为 originalUser 的变量中
let originalUser = Auth.auth().currentUser
Then, in the completion handler of creating a new user, use the updateCurrentUser method to restore the original user
然后,在创建新用户的完成处理程序中,使用 updateCurrentUser 方法恢复原始用户
Auth.auth().updateCurrentUser(originalUser, completion: nil)
回答by Jon Sakas
Here is a simple solution using web SDKs.
这是一个使用 Web SDK 的简单解决方案。
- Create a cloud function (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;
- Call this function from your app
- 从您的应用程序调用此函数
import firebase from 'firebase/app';
const createUser = firebase.functions().httpsCallable('createUser');
createUser({ email, password })
.then(console.log)
.catch(console.error);
- Optionally, you can set user document information using the returned uid.
- 或者,您可以使用返回的 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);
回答by fkvestak
Android solution (Kotlin):
安卓解决方案(Kotlin):
1.You need FirebaseOptions BUILDER(!) for setting api key, db url, etc., and don't forget to call build() at the end
1.设置api key、db url等需要FirebaseOptions BUILDER(!),最后不要忘记调用build()
2.Make a secondary auth variable by calling FirebaseApp.initializeApp()
2.通过调用 FirebaseApp.initializeApp() 创建一个二级 auth 变量
3.Get instance of FirebaseAuth by passing your newly created secondary auth, and do whatever you want (e.g. createUser)
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()
}
}
}
回答by Nico
The Swift version:
斯威夫特版本:
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(...)
}