How Reauthenticate User at Firebase - android

I'm trying to update the user's email, but firebase requires a recent login for this, so I tried to use the method that was in the firebase documentation, but the problem is how I can pass the password user? I do not keep the password in db, and I can not get it from the firebase, so I do not know how I can pass the password.
The solution I thought is to ask the user to enter the password, so I tried to use a field to enter the password but it still does not work, so how can I pass the password to the firebase and reauthenticate the user to change the data?

You need to re-authenticate a user, referring to documentation.
For instance you have a field where the user types his password, let's say it`s an EditText etPassword, and you have user email in SharedPreferences
So the code to re-authenticate will look like this:
AuthCredential credential = EmailAuthProvider
.getCredential(SharedPreferences.getmail(),etPassword.getText().toString());
// 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) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
updateUserEmail();
} else {
// Password is incorrect
}
}
});
where updateUserEmail() is
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail("user#example.com")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
}
}
});

Related

Android Firebase can update user email once only

Currently i'm making user email and password update for my homework app.
the problem is the Email can only be update ONCE. after that it just give information such as
D/FirebaseApp: Notifying auth state listeners.
D/FirebaseApp: Notified 1 auth state listeners.
(there is no issue with updating password. only email)
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication //User Sekarang punya email
AuthCredential credential = EmailAuthProvider.getCredential(emailCurrent, passCurrent); // Current Login Credentials \\
// 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()) {
Toast.makeText(getApplicationContext(), "User re-authenticated.", Toast.LENGTH_SHORT).show();
//Now change your email address \\
//----------------Code for Changing Email Address----------\\
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "User email address updated.", Toast.LENGTH_SHORT).show();
System.out.println("Email Updated");
}
}
});
//----------------------------------------------------------\\
} // End of isSuccessful
} // End of onComplete
});
Expected can update email unlimitedly.
Currently can only update email once.

Firebase Authentication (email and password) How to check if user still exists?

I'm using Firebase Authentication in my app (email and password auth).
In the onStart() method of my Login activity I retrieve the current user using:
FirebaseUser currentUser = mAuth.getCurrentUser();
The problem comes when the user is deleted from the database, the mAuth.getCurrentUser() method still retrieves the user and allows authentication.
How can I check if the user still exists?
Thx!
Try using something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("email").addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// used "email" already exists and is not deleted
} else {
// User does not exist. Add here your logic if the user doesn't exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or check some of the following SO questions and answers:
Firebase authentication for checking if the user exists in the database or not
Firebase Auth - with Email and Password - Check user already registered
You can use getInstance. This worked for me fine. You don't get an instance with it.
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
Delete the userdata and make the currentuser null:
Follow the below code.
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted.");
//Remove the information f the user from database.
}
}
});
The code below works great on android to confirm if the Firebase Auth user still exists (has not been deleted or disabled) and has valid credentials.
Deleting the Auth user from the firebase console does not revoke auth tokens on devices the user is currently logged in as the token is cached locally. Using reload() forces a check with the firebase auth server.
currentUser.reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//User still exists and credentials are valid
}else {
//User has been disabled, deleted or login credentials are no longer valid,
//so send them to Login screen
}
}
});

Google Facebook and email Auth in android app with Firebase

I am developing an android app using Firebase and I want to add 3 Login option: Facebook, Google and email (and password).
I want to give the user 3 options when he wants to login: sign in with email and password or login with Facebook or Google.
If the user chooses Facebook or Google, I want to check if the email of the Facebook/Google belongs to another credential, and if it is, I want to link the user with the new credential. Else, sign-in in the normal way.
For example, let's assume that I have Facebook and Google accounts with the same email, and I have already signed-in through email and password auth. When I will click the Facebook login button, the app will notice that my email belongs to existing user and will connect my facebook account to my existing user (probably with user.linkWithCredential()). The same if I tries to sign-in via Google, or if I create new user using email and password if he already logged-in via Google...
I have tried to do something like this, but I still not sure how to get the other credential (without asking the user to sign-in from different provider) or the firebase existing user, in order to link it with the new credential.
authResultTask = mAuth.signInWithCredential(credential).addOnCompleteListener(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, "signInWithCredential:success");
loggedIn(LoginType.FACEBOOK);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
mAuth.fetchProvidersForEmail(email /*not sure how to get the email also*/).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
#Override
public void onComplete(#NonNull Task<ProviderQueryResult> task) {
if (task.isSuccessful()) {
if (task.getResult().getProviders().contains(
GoogleAuthProvider.PROVIDER_ID)) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Link initial credential to existing account.
getExistingUser()/*somehow get the existing user*/.linkWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
}
});
} else {
makeToast(R.string.error_occurred);
disable.enableAndRemoveProgress();
}
}
});
}
} else {
makeToast(R.string.error_occurred);
}
}
});
} else {
makeToast(R.string.error_occurred);
}
}
}
});
Do you have any idea how it can be done?

get the password from the User

So I am trying to implement a change password feature. I am able to to do it using updatePassword (newPassword) method. I would like to do some verification before this.So for example when the user wants to change his password, he presses a button and then:
User enters current password
User enters new password
User enters new password again.
How do I verify that the current password the user inputted is correct? There does not seem to be a method that gets me the current password of the user to compare it with.
What you are looking for is "Re-authenticate a user" which is discussed in Firebase's authentication documention. The idea is that you must have the user re-enter their old information into the user.reauthenticate method and firebase will verify the information and you continue operations in onComplete if successful, or firebase sends you an exception. You would use updatePassword in onComplete like below. Your UI would look like its one transaction but really its reAuthenticate -> updatePassword. You additionally may be able to assume the user username/email based on how you store user information.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String newPassword = "SOME-SECURE-PASSWORD";
// 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("user#example.com", "password1234");
// The email and password should be extracted from an EditText
// 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) {
Log.d(TAG, "User re-authenticated.");
user.updatePassword(newPassword)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User password updated.");
}
}
});
}
});

How to send verification email with Firebase?

I am signing up my users using Firebase's email and password method. like this:
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser signed = task.getResult().getUser();
writeNewUser(signed.getUid());
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
updateUser(b);
}
}, 3000);
} else {
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
onSignupFailed();
}
}, 3000);
}
}
});
After the user's email has been successfully registered, I would like Firebase to send a verification email. I know this is possible using Firebase's sendEmailVerification. In addition to sending this email, I want the user's account to be disabled until they verify the email. This would also require using Firebase's isEmailVerified feature. However, I have been unsuccessful in getting Firebase to send the verification email, I have not been able to figure out to get it to disable and enable the account sending the verification email and after it has been verified.
This question is about how to use Firebase to send the verification email. The OP is unable to figure out how to disable and enable the account sending the verification email and after it has been verified.
Also, this is not properly documented in the firebase documentation. So I am writing a step by step procedure that someone may follow if he/she is facing the problem.
1) User can use createUserWithEmailAndPassword method.
Example:
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("TAG", "createUserWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// Show the message task.getException()
}
else
{
// successfully account created
// now the AuthStateListener runs the onAuthStateChanged callback
}
// ...
}
});
If the new account was created, the user is also signed in, and the AuthStateListener runs the onAuthStateChanged callback. In the callback, you can manage the work of sending the verification email to the user.
Example:
onCreate(...//
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
// NOTE: this Activity should get onpen only when the user is not signed in, otherwise
// the user will receive another verification email.
sendVerificationEmail();
} else {
// User is signed out
}
// ...
}
};
Now the send verification email can be written like:
private void sendVerificationEmail()
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// email sent
// after email is sent just logout the user and finish this activity
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(SignupActivity.this, LoginActivity.class));
finish();
}
else
{
// email not sent, so display message and restart the activity or do whatever you wish to do
//restart this activity
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
}
}
});
}
Now coming to LoginActivity:
Here if the user is successfully logged in then we can simply call a method where you are writing logic for checking if the email is verified or not.
Example:
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//Log.d("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
//Log.w("TAG", "signInWithEmail:failed", task.getException());
} else {
checkIfEmailVerified();
}
// ...
}
});
Now consider the checkIfEmailVerified method:
private void checkIfEmailVerified()
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified())
{
// user is verified, so you can finish this activity or send user to activity which you want.
finish();
Toast.makeText(LoginActivity.this, "Successfully logged in", Toast.LENGTH_SHORT).show();
}
else
{
// email is not verified, so just prompt the message to the user and restart this activity.
// NOTE: don't forget to log out the user.
FirebaseAuth.getInstance().signOut();
//restart this activity
}
}
So here I m checking if the email is verified or not. If not, then log out the user.
So this was my approach to keeping track of things properly.
send verification to user's Email
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification();
check if user is verified
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
boolean emailVerified = user.isEmailVerified();
Use FirebaseAuth.getInstance().getCurrentUser().sendEmailVerification() and FirebaseAuth.getInstance().getCurrentUser().isEmailVerified()
There is no way to disable the account via the Firebase SDK. The thing you can do is use the GetTokenResult containing the Firebase Auth ID Token and validate it against your custom backend or set a flag to Firebase database corresponding to that user. Personally I'd go with the flag in the Firebase database
For sending email link with Firebase first you need to grab FirebaseAuth instance
using the instance we create user on Firebase through:
firebaseauth.createUserWithEmailAndPassword(email,pass);
When method return success we send verification link to user using Firebase user instance as follows:
final FirebaseUser user = mAuth.getCurrentUser();
user.sendEmailVerification()
See this link: https://technicalguidee.000webhostapp.com/2018/10/email-verification-through-link-using-firebase-authentication-product-android.
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(this, "please check email for verification.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}else{
Toast.makeText(this, task.getException().getMessage() , Toast.LENGTH_SHORT).show();
}
}
});
For Kotlin
val user: FirebaseUser? = firebaseAuth.currentUser
user?.sendEmailVerification()

Categories

Resources