Firebase Auth identify if the user entered the wrong password - android

I am currently using Firebase password authentication and this is my login method its very common.
I have an else block statement that tells the user that the login is not successful but that doesn't tell the user what specifically is wrong. How can I identify if the user entered the wrong password?
private void signIn(String email, String password, final View view) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgress();
// [START sign_in_with_email]
fLogInAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
progressDialog.dismiss();
FirebaseUser currUser = fLogInAuth.getCurrentUser();
establishUI(currUser);
} else {
progressDialog.dismiss();
establishUI(null);
Snackbar.make(view, "Unable to login, Please try again in a few moments",Snackbar.LENGTH_LONG).show();
}
}
});
}

Use task.getException().getLocalizedMessage() inside onComplete() to get error message.

Related

How to login user with otp after sign out using firebase in android

I have created an android app where I sign up user with otp verification and store user with email and password details in firebase.
but when user logout in login section I try to login user with email and password but at a time firebase thrown error user not found.
I sign up user in firebase with otp verification method and login user with authsigninwithemailandpassword method of firebase.
Here is my code:
I pass value to the otpverification.java file
RegisterPage.java :-
Intent i = new Intent(getApplicationContext(), OtpVerificationPage.class);
i.putExtra("phoneNumber", binding.ccp.getFullNumberWithPlus());
i.putExtra("userName", binding.userNameET.getText().toString());
i.putExtra("userEmail", binding.emailET.getText().toString());
i.putExtra("userPassword", binding.passwordET.getText().toString());
startActivity(i);
Toast.makeText(RegisterPage.this, "Please Verify With Otp", Toast.LENGTH_SHORT).show();
OtpVerification.java
private void sendOtp() {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
userPhoneNo,
60,
TimeUnit.SECONDS,
OtpVerificationPage.this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(OtpVerificationPage.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(#NonNull String verificationId, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(verificationId, forceResendingToken);
progressDialog.dismiss();
getbackEndOtp = verificationId;
Toast.makeText(OtpVerificationPage.this, "Otp Sent Successfully", Toast.LENGTH_SHORT).show();
}
}
);
}
Send otp method now verification method :-
if (getbackEndOtp != null) {
//Check User otp with google otp
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(getbackEndOtp, userEnterdOtp);
//Second progress dialog display
progressDialog1.show();
//Authenticate user here
FirebaseAuth.getInstance().signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//Generate User with user model class
FirebaseUser userId = FirebaseAuth.getInstance().getCurrentUser();
UserModel userModel = new UserModel();
userModel.setUserId(userId.getUid());
userModel.setUserName(userName);
userModel.setUserEmail(userEmail);
userModel.setUserContactNo(userPhoneNo);
userModel.setUserPassword(userPassword);
//If user authentication task is successful this method run
if (task.isSuccessful()) {
progressDialog1.dismiss();
database.getReference()
.child("Users")
.child(userId.getUid())
.setValue(userModel)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Intent intent = new Intent(OtpVerificationPage.this, MainActivity.class);
startActivity(intent);
finishAffinity();
}
});
} else {
Toast.makeText(OtpVerificationPage.this, "Please enter otp which send to your mobile no", Toast.LENGTH_SHORT).show();
}
}
});//Authentication Method Complete here
}
Otp verification completely works and store user data in firebase
Data store completely with in realtime database.
Now problem arise after user logout verification with email and password not work
but i already store user with email and password.
LoginActivity.java
//Firebase
auth = FirebaseAuth.getInstance();
//Check User
binding.signInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.show();
String email = binding.emailET.getText().toString();
String password = binding.passwordET.getText().toString();
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Intent intent = new Intent(LoginPage.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(LoginPage.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
Now when i click on sign in button this error arise:
how to solve this error?

How do I keep a user logged in after they logged in at least once?

How do I keep user loged in after they have signed in one time. I have a register activity that allows the the user to provide their email address and password, and once the user clicks submit an email confirmation is sent and then takes the user to the Login Activity. However once the user gets to the Login Activity they are automatically signed in. I would first like for them to validate their email first and then be signed in and stayed signed in unless they log out. I found some answers on stack-overflow about how to keep the user signed in and how to check if they validated their email but the code that I have skips the validation step and just signs the user in once taken to the login activity.
**Check to see if user enters correct credetials **
public void loginUser(View view) {
if (userEmailEditText.getText().toString().trim().equals("") || userPasswordEditText.getText().toString().trim().equals("")) {
Toast.makeText(LoginActivity.this, "Enter the required information!", Toast.LENGTH_SHORT).show();
} else {
mAuth.signInWithEmailAndPassword(userEmailEditText.getText().toString(), userPasswordEditText.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
checkUserStatus();
} else {
Toast.makeText(LoginActivity.this, "incorrect info", Toast.LENGTH_SHORT).show();
}
}
});
}
}
**Keeps the user singed in i called this method in onCreate**
public void keepUserSignedIn() {
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
private void createUser() {
mAuth.createUserWithEmailAndPassword(user.getUserEmail(), user.getUserPassword())
.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
//save user info if registration was successful
saveUserInfo();
sendVerificationEmail();
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Log.i("error", task.getResult().toString());
// If sign in fails, display a message to the user.
Toast.makeText(RegisterActivity.this, "Error occurred", Toast.LENGTH_SHORT).show();
}
}
});
}
public void sendVerificationEmail() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Verify your email...", Toast.LENGTH_SHORT).show();
mAuth.signOut();
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
}
});
}
}
//upload user's credetinals to firebase...
public void saveUserInfo() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
//rogressDialog.show();
final String userId = mAuth.getCurrentUser().getUid();
final StorageReference storageRef = FirebaseStorage.getInstance().getReference().child("ProfileImages").child(userId);
storageRef.putFile(selectedImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
deviceToken = FirebaseInstanceId.getInstance().getToken();
url = uri.toString();
userDictionary.put("devicetoken", deviceToken);
userDictionary.put("name", user.getUserName().trim());
userDictionary.put("email", user.getUserEmail().trim());
userDictionary.put("lastName", user.getLastName().trim());
userDictionary.put("profileimage", url);
userDictionary.put("user", userId);
mDatabase.child(userId).setValue(userDictionary);
progressDialog.dismiss();
}
//handles error
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
Authenticating the user with Firebase Authentication does not require them to have validated their email address. The two steps are separate, and for good reason.
Once a user signs in, they will normally stay signed in until they sign out. Firebase restores their authentication state when you restart the app, so in most cases things should run smoothly.
If you want a user to only be sent to a certain activity if they've signed in with an account with a verified email address, you can do so with:
FirebaseUser user = mAuth.getCurrentUser();
if (user != null && user.isEmailVerified()) {
...
}

FireBase Authentication mAuth.createUserWithEmailAndPassword(email, password) error

So I'm trying to add an Authentication and Sign in service to my app, I'm following all of the steps told on FireBase although I can't get through this part, it says that the error is
createUserWithEmailAndPassword(Java.lang.String, Java.lang.String) in
FireBaseAuth cannot be applied to (Android.widget.text,
Android.widget.text)
Thanks in advance for any help given. The code is the following:
public void Register(View view) {
Intent intent = new Intent(LoginActivity.this, BottomActivity.class);
startActivity(intent);
attemptLogin();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener( this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d( TAG, "createUserWithEmail:success" );
FirebaseUser user = mAuth.getCurrentUser();
updateUI( user );
} else {
Log.w(TAG, "createUserWithEmail:failed");
Toast.makeText(LoginActivity.this, "Authentication failed", Toast.LENGTH_SHORT).show();
updateUI( null );
}
}
} );
}
email/password:
private AutoCompleteTextView email;
private EditText password;
use like this
mAuth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString()).addOnCompleteListener( this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d( TAG, "createUserWithEmail:success" );
FirebaseUser user = mAuth.getCurrentUser();
updateUI( user );
} else {
Log.w(TAG, "createUserWithEmail:failed");
Toast.makeText(LoginActivity.this, "Authentication failed", Toast.LENGTH_SHORT).show();
updateUI( null );
}
}
} );
From reading the error you're getting, it's saying that the type of the parameters you're passing are not matching what the method expects. It expects String objects. So you'd need to extract that value from your TextView and EditText.
Try passing email.getText().toString() and password.getText().toString as parameters instead of email and password.
So
mAuth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString())...
The answer is very simple you should add a classpath 'com.google.gms:google-services:4.3.8' in dependencies of built.gradle
and then add id 'com.google.gms.google-services' in built.gradle(app)
that's all.

Firebase User Verification Email

I am using Firebase as the Backend for an Mobile Android Application. When a User registers, I would like to have a verification email sent to that user.
When the User Clicks the "SignUp" button, the following logic is run through: First of all a number of variables are set from the filled in boxes. Then a few checks are performed on validity of the filled in parameters. If the checks are passed, a user is created in the Database. This is all functioning..
Then I would like to send a verification email to the user to check if the email is valid. I have also put this in the onClick method of the Button but this is not functioning yet.
I do not receive the verification email.
What is the reason behind this and the fix?
My onCreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_sign_up_page);
setFontType();
screen = (EditText)findViewById(R.id.SchermNaam);
mail = (EditText)findViewById(R.id.EmailAdres);
knop = (Button)findViewById(R.id.SignUp_Button_SignUp);
firebaseAuth = FirebaseAuth.getInstance();
}
The onClick method for the "SignUp" Button:
public void onClickSignUpPage(View view){
String schermnaam = screen.getText().toString().trim();
String emailadres = mail.getText().toString().trim();
String paswoord = pass.getText().toString().trim();
if(TextUtils.isEmpty(schermnaam)){
Toast.makeText(this,"Schermnaam invullen", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(emailadres)){
Toast.makeText(this,"Email invullen",Toast.LENGTH_SHORT).show();
return;
}
if(!schermnaam_ok(schermnaam)){
Toast.makeText(this,"schermnaam minstens 5 en maximum 15 tekens", Toast.LENGTH_SHORT).show();
return;
}
if(!paswoord_ok(paswoord)){
Toast.makeText(this,"paswoord tussen 6-12 karakters en minstens 1 cijfer", Toast.LENGTH_SHORT).show();
return;
}
firebaseAuth.createUserWithEmailAndPassword(emailadres.trim(),paswoord)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(SignUpPage.this, "Nieuwe Speler Geregistreerd", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUpPage.this, SignInPage.class);
startActivity(intent);
}
else {
FirebaseAuthException e = (FirebaseAuthException) task.getException();
Toast.makeText(SignUpPage.this,"Fout in de SignUp"+e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("LoginActivity", "Failed Registration", e);
return;
}
}
});
FirebaseUser user = firebaseAuth.getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
}
Changed it up to a sequential procedure, as suggested by the post quoted by #cramopy. Thank you for this!
Now you first need to "Sign Up" as a user, and then verify in another step, through another button. Then I receive the confirmation email.
Here my code for the onClick method for the 2 Buttons.. From a UX point of view, need to look at how to position the buttons. This is a functional viewpoint.
public void onClickSignUpPage(View view){
String schermnaam = screen.getText().toString().trim();
String emailadres = mail.getText().toString().trim();
String paswoord = pass.getText().toString().trim();
if(TextUtils.isEmpty(schermnaam)){
Toast.makeText(this,"Schermnaam invullen", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(emailadres)){
Toast.makeText(this,"Email invullen",Toast.LENGTH_SHORT).show();
return;
}
if(!schermnaam_ok(schermnaam)){
Toast.makeText(this,"schermnaam minstens 5 en maximum 15 tekens", Toast.LENGTH_SHORT).show();
return;
}
if(!paswoord_ok(paswoord)){
Toast.makeText(this,"paswoord tussen 6-12 karakters en minstens 1 cijfer", Toast.LENGTH_SHORT).show();
return;
}
firebaseAuth.createUserWithEmailAndPassword(emailadres.trim(),paswoord)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(SignUpPage.this, "Nieuwe Speler Geregistreerd", Toast.LENGTH_SHORT).show();
}
else {
FirebaseAuthException e = (FirebaseAuthException) task.getException();
Toast.makeText(SignUpPage.this,"Fout in de SignUp"+e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("LoginActivity", "Failed Registration", e);
return;
}
}
});
AddDataFireBase();
}
public void onClickVerify(View view){
FirebaseUser user = firebaseAuth.getCurrentUser();
assert user != null;
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
else {
Log.e(TAG, "sendEmailVerification", task.getException());
Toast.makeText(SignUpPage.this,
"Failed to send verification email.",
Toast.LENGTH_SHORT).show();
}}
});
Intent intent = new Intent(SignUpPage.this, SignInPage.class);
startActivity(intent);
}
Your code should work. But I suggest you to follow the next steps to verify the email:
Create account
Check if creation was successful
Check if the email is verified with user.isEmailVerified()
Reload your user to update the instance with user.reload(). You should do this because some methods on Firebase ask you to reload or reauthenticate the user before realize some operations. Reload in this case will update the cache and data of your user.
Send the email using sendEmailVerification()
Something like:
authInstance.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (it.isSuccessful) {
//Create accountData in the database
if (it.result!!.user.isEmailVerified) {
it.result!!.user.reload()
.addOnCompleteListener {
if (it.isSuccessful) {
authInstance.currentUser!!.sendEmailVerification()
.addOnCompleteListener {
Log.i("TAG", "Yay! verificationSent")
}
} else {
//Manage error
}
}
}
} else {
//Manage error
}
}
Also, you should know that sometimes the email verification takes some time in Debug environments(at least from my experience I have saw delays of 1-3 minutes, but never on release versions).
Finally, before call user.verify() you should need to call again user.reload() to update the data of your user in the Firebase Cache, if not, even if you have click on Verify my email on the email sent to your account, the FirebaseAuthor.currentUser().isEmailVerified() will continue returning you false.

How to delete a registered user by using firebase auth in android studio?

I have created the Register method using firebase authentication user register method.
How to delete a registered user by using firebase auth and android studio?
private void registerUser(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user successfully registered and logged in
Toast.makeText(MainActivity.this, "Registered Successfully",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
finish();
startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
}else{
Toast.makeText(MainActivity.this, "Could Not Register. Please Try Again Later",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
private void deleteUser(){
// TODO: Fill this method
}
You can use delete() method to remove the desired user from the Firebase. Please use this code:
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
AuthCredential authCredential = EmailAuthProvider.getCredential("user#example.com", "password1234");
firebaseUser.reauthenticate(authCredential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
firebaseUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted!");
}
}
});
}
});

Categories

Resources