Создайте документ в firestore с именем документа имя пользователя и полем электронная почта .
профили
- fatalcoder524 // имя пользователя
- электронная почта: test@test.com // электронная почта для проверки
- dob: 12/12/12 // другие данные
Сначала проверьте, присутствует ли имя пользователя в firestore.
- Если существует, используйте адрес электронной почты в firestore и пароль пользователя для проверки.
- Если нет, попросите пользователя зарегистрироваться.
Пример кода: (Регистрация)
String email; //user input
String username; //user input
String password; //user input
Map<String, Object> user = new HashMap<>();
user.put("email", email); // data to add to firestore
db.collection("profiles").document(username) //username is set as firestore document name, profiles is the collection name
.set(user) //Store the email in above document.
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) // If data is added successfully
{
mAuth.createUserWithEmailAndPassword(email, password) // create account
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
}
}
});
}
});
Пример кода: (Вход)
String username; //get username from user
String password; //get password from user
DocumentReference docRef = db.collection("profiles").document(username); //get doc reference
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) // if username is present
{
String email=document.getData().email; //get email from document
mAuth.signInWithEmailAndPassword(email, password) //signin with email
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) // if password and email id matches
{
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document");
//add code (user not found/registered)
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
Модификация вашего кода:
FirebaseFirestore db = FirebaseFirestore.getInstance();
private void registerUser (){
String email = editTextEmail.getText().toString().trim();
String username = editTextUsername.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email is required");
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError(("Please enter a valid email"));
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError("Your password must be at least 6 characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
Map<String, Object> user = new HashMap<>();
user.put("email", email);
db.collection("profiles").document(username) //username is set as firestore document name, profiles is the collection name
.set(user) //Store the email in above document.
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) // If data is added successfully
{
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull final Task<AuthResult> task) {
if (task.isSuccessful()) {
// send user verification link using firebase
FirebaseUser user = mAuth.getCurrentUser();
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(ChildSignUpActivity.this, "Verification Email Has Been Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();;
}
});
Toast.makeText(getApplicationContext(), "User Register Succesfull", Toast.LENGTH_SHORT).show();
} else {
if(task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "User already exists", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT);
}
}
}
});
}
});
}