Android: Firebase email verification [duplicate] - android

This question already has an answer here:
Firebase Authentication: Verify email before sign up
(1 answer)
Closed 2 years ago.
Is there any way to check email is verified or not before the login. I am sending verification links through Firebase email authentication its work successfully. But I tried to check is Email verified or not.
final FirebaseUser user = firebaseAuth.getCurrentUser();
if (user.isEmailVerified()) {
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please verify your email!", Toast.LENGTH_SHORT).show();
}
}
});

As far as I know, the user needs to be signed in. There is no other way to get a User object so that you can call the isEmailVerified method on it.

Related

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 user's email address method updateEmail is not working correctly

I also used the re-authentication method before using before the updateEmail method. Everything working correctly. Even the toast message in the updateEmail also appears as expected but there is no change in the firebase database of the user.
It detects the already existed email in the firebase database and show a toast of "Email already exist".
It also works fine in checking the email from firebase and if it doesn't collide then it shows a toast message "Email upadated".
But still it doesn't change the email in the firebase database.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(mAuth.getCurrentUser().getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User re-authenticated.");
mAuth.fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if (task.isSuccessful()) {
try {
if (task.getResult().getSignInMethods().size() == 1) {
Log.d(TAG, "onComplete: This will return the signin methods");
Toast.makeText(getActivity(), "The email is already exist", Toast.LENGTH_SHORT).show();
}else{
Log.d(TAG, "onComplete: Email is not present. User can change it");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(getActivity(), "The email updated.", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch(NullPointerException e) {
Log.e(TAG, "onComplete: NullPointerException" + e.getMessage());
}
}
}
});
} else {
Log.d(TAG, "onComplete: User re-authentication failed.");
}
}
});
This mAuth.getCurrentUser().getEmail() will give you the email from the Firebase built-in user class and not from the database itself.
And I cant see any way that you have changed the email in the database itself.
This function updates the email in the Firebase user class which can be seen in the "Authentication" section of your Firebase console
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(getActivity(), "The email updated.", Toast.LENGTH_SHORT).show();
}
}
});
To update the data in database you have to follow this
Once again I am repeating you are updating the email of a user in the Firebase user class not the actual database. As mentioned, updated email will only be visible in "Authentication" section of Firebase console and to make data change in "database" you have to follow the link.

Firebase Send Verification Email doesn't work

I was wondering if anybody else has the same problem, I'm working on a project using Firebase Email and Password for login, everything works fine except Verification Email, here's the code down there does anybody else has this problem? is it belong to Google? or it's something that I'm doing it wrong?
because the signUp method works fine and the user will be created after user press the Register button, but sendVerificationEmail method never been called
this is the signUp method which includes sendVerificationEmail method:
if (checkSignUpFormFields()) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(LaunchActivity.this, "Your account successfully created", Toast.LENGTH_SHORT).show();
sendVerificationEmail();
FirebaseAuth.getInstance().signOut();
} else {
Toast.makeText(LaunchActivity.this, "something went wrong, Check your information",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
and this is the method for sending verification method:
private 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(LaunchActivity.this, "Verification Email has been sent.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LaunchActivity.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
There's some issue with Firebase itself, I received an Email for a registration I've made about an hour ago, it's just taking so long more than an hour or so, and must be Googles issue.

Firebase Auth identify if the user entered the wrong password

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.

Check if email and password are correct Firebase

I'm currently working on an app that shows users in a listview and when you click on a user, you get to see the details.
Now you can 'add' users by filling in editText field with his or her info. Now I want that only the person himself can add his or her info. I added a editText asking for your email and an editText asking for a password. These credentials should match an account previously created in the app in Firebase. I do not seem to accomplish it.
This is my code:
String email2 = mEmailField.getText().toString();
String pw = mPassword.getText().toString();
firebaseAuth.signInWithEmailAndPassword(email2, pw).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
When the user fills in his email and password everything works, but when the incorrect password is entered, it works as well and that should not happen. What did I do wrong?
Inside OnComplete check if the Authentication was successful.
public void onComplete(#NonNull final Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Authentication Successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Authentication failed.",Toast.LENGTH_SHORT).show();
}
}
mAuth.signInWithEmailAndPassword(et_LogIn_Email.getText().toString(),et_LogIn_Pasword.getText().toString())
.addOnCompleteListener((EntryActivity) requireActivity(), new OnCompleteListener<AuthResult>() {
#SuppressLint("SetTextI18n")
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText((EntryActivity) requireActivity(), "LogIn...", Toast.LENGTH_SHORT).show();
loadingDialog.stopLoading();
gotoUiPage();
} else {
Toast.makeText((EntryActivity) requireActivity(), "Error! try again...", Toast.LENGTH_SHORT).show();
tv_LogIn_warning.setText("Enter Carefully!...");
loadingDialog.stopLoading();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tv_LogIn_warning.setText(e.getMessage());
}
});
onFailureListener provide an exception by which you handle it.

Categories

Resources