Попробуйте сыграть с
margin: 0 auto;
Если вы хотите также центрировать свой текст, попробуйте использовать:
text-align: center;
Вот адаптация 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")
}
Я получил очень умное обходное решение André , работающее в Objective-C с использованием SDK Firebase iOS:
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];
}];
Я попробовал несколько разных вариантов создания нескольких пользователей из одной учетной записи, но это, безусловно, лучшее и самое простое решение.
Оригинальный ответ Nico
Сначала сконфигурируйте firebase в файле AppDelegate.swift
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()
}
}
}
}
Если вы используете Polymer и Firebase (полимерный огонь), см. этот ответ: https://stackoverflow.com/a/46698801/1821603
По существу вы создаете вторичный <firebase-app>
для обработки новой регистрации пользователя, не затрагивая текущего пользователя.
Android-решение (Kotlin):
// 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 только что выпустила свой SDK firebase-admin, который позволяет использовать код на стороне сервера для этого и других распространенных административных прецедентов. Прочтите инструкции по установке , а затем погрузитесь в документацию по созданию пользователей .
исходный ответ
В настоящее время невозможно. Создание пользователя Email + Password автоматически подписывает нового пользователя.
Версия 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(...)
}
Я только что создал функцию 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();
});
Я столкнулся с той же проблемой, и я решил это следующим образом:
Когда пользователь вводит логин, я сохраняю адрес электронной почты и пароль в общих настройках. И после создания пользователя я снова вхожу в систему с помощью электронной почты и пароля, которые я сохранил ранее.
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();
}
}
});
У меня была аналогичная проблема, поэтому я задал вопрос в сообществе Firebase Slack. Я реализовал это и работает как шарм.