Re-authenticate failed Firebase Android - android

I'm trying to create Change Password feature... but I don't know why getting the error, although I type the correct password. It's always returning failed.
I follow this code from
Manager Users Firebase
and this is my code
edtOldPass = (TextInputLayout) findViewById(R.id.edt_oldpass);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String email = mCurrentUser.getEmail();
String pass = edtOldPass.getEditText().toString();
AuthCredential credential = EmailAuthProvider.getCredential(email, pass);
mCurrentUser.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent newpassIntent = new Intent(ReAuthActivity.this, ChangePassActivity.class);
startActivity(newpassIntent);
} else {
Toast.makeText(ReAuthActivity.this, "Incorrect Password", Toast.LENGTH_SHORT).show();
}
}
});

This code to get the password is not correct:
String pass = edtOldPass.getEditText().toString();
Calling getEditText() on a TextInputLayout returns the contained EditText widget, not the string value of the EditText.
Change it to this:
String pass = edtOldPass.getEditText().getText().toString();

Related

Firebase Auth - no email from google sign in provider

Email is null when signing in with Google provider
I have tried with 3 Gmail accounts - 1 of them is OK, but with 2 I get null.
All three are listed in the console properly with the account's Email as "Identifier"
currentUser = FirebaseAuth.getInstance().getCurrentUser();
String Email = currentUser.getEmail();
code creating auth:
providers = Arrays.asList(
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.FacebookBuilder().build()
);
startActivityForResult(
AuthUI.getInstance().createSignInIntentBuilder()
.setAvailableProviders(providers)
.setIsSmartLockEnabled(false)
.build(),MY_REQUEST_CODE);
I had the same problem, no Google email address was returned.
After adding the scope email:
var provider = new this.$firebase.auth.GoogleAuthProvider();
provider.addScope('email');
it was returning the email address in the providerdata.
The same problem I had also with Facebook login. I needed to add the scope like this
var provider = new this.$firebase.auth.FacebookAuthProvider();
provider.addScope("email");
Try this one, I had the same issue, but on applying GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(LoginActivity.this); after authentication with firebase, the issue got resolved.
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(credential)
.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, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
String a="Email: "+user.getEmail()
+"\nName: "+user.getDisplayName()+"\nL= "+user.getProviderData();
//Here I got email field as null: 1 of them is OK, but with remaining I get null
Log.d(TAG, "onComplete: USER DATA:\n"+a);
// Add this code to get current sign-in user info
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(LoginActivity.this);
if (acct != null) {
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Log.d(TAG, "onComplete: RESULT--> "+"Name: "+personName+"\n"+
"Email: "+personEmail+"\n"+
"ID: "+personId+"\n"+
"Photo: "+personPhoto+"\n"+
"PersonGiven Name: "+personGivenName+"\n");
}
// updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Snackbar.make(r, "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
// updateUI(null);
}
// ...
}
});
}
In my code, I can see that <currentUser.providerData> contains two lists.
After comparison, the 0th list had no email value, but contained displayName and photoUrl. The first list had all three values. So I'm using the first value. But I don't know the exact reason.
I copied the code from the testing project to my main project and the problem is resolved. I don't understand why.

Firebase remote config, cant get value. Android

I have created some test project for learning Firebase remote config. This is settings in firebase https://monosnap.com/file/0xgQCL7oo7lyOjBs8CG3kZO0szBXh6 . Bellow my code:
final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
config.setConfigSettings(configSettings);
String onlineVersion = FirebaseRemoteConfig.getInstance().getString("android_current_version");// empty string
I dont know why i cant get value from firebase
Maybe you need to fetch the remote config first:
config.fetch(cacheExpiration)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Fetch Succeeded",
Toast.LENGTH_SHORT).show();
// After config data is successfully fetched, it must be activated before newly fetched
// values are returned.
mFirebaseRemoteConfig.activateFetched();
} else {
Toast.makeText(MainActivity.this, "Fetch Failed",
Toast.LENGTH_SHORT).show();
}
String onlineVersion = FirebaseRemoteConfig.getInstance().getString("android_current_version");// empty string
}
})
In the "onComplete" method, you can get the remote config info
check this: Remote Config

Using Firebase return an image that is linked to a user account

I am currently working on an app using android studio and currently have a working login using Firebase user authentication. However, I am trying to have an image appear on the screen when the user logs after using this authentication. I want this image to be linked to that specific user. Is this possible?
You can set a photo url on a user's firebase profile with the following code:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("Jane Q. User")
.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
You would then retrieve the user's profile information (including their photo URL) like so:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// Check if user's email is verified
boolean emailVerified = user.isEmailVerified();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
String uid = user.getUid();
}
More info: https://firebase.google.com/docs/auth/android/manage-users
If you're using oAuth authentication and want to retrieve their profile photo from facebook, you'll find more information about how to do that at the link below:
https://firebase.google.com/docs/auth/android/facebook-login

Firebase setDisplayName has no effect

I'm using Firebase's custom authentication.
I'm trying to set a user's username with:
UserProfileChangeRequest userProfileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName("Hello")
.build();
assert currentUser != null;
currentUser.updateProfile(userProfileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(UsernameAndProfilePictureChooserActivity.this, "Success. Username: " + getUsername(), Toast.LENGTH_SHORT).show();
}
else {
throw new Error(task.getException().getMessage(),task.getException().getCause());
}
}
});
But it has no effect.
The Toast message (Toast.makeText(UsernameAndProfilePictureChooserActivity.this, "Success. Username: " + getUsername(), Toast.LENGTH_SHORT).show(); gets called, but getUsername(), which is FirebaseAuth.getInstance().getCurrentUser().getDisplayName() returns null.
Closing the app then re-opening it doesn't work.
Why is this happening?
Try to update the version of your firebase auth library.
I am using com.google.firebase:firebase-auth:10.2.0 and it works for me.

How to add DisplayName with email + password authentication in Firebase? Android

private void registerUser(){
String emailId = email.getText().toString().trim().toLowerCase();
String password = pass.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(emailId,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Registration Successful",Toast.LENGTH_SHORT).show();
//show chatroom
finish();
startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
}
else{
Toast.makeText(MainActivity.this,"Registration Failed. Please try again",Toast.LENGTH_SHORT).show();
}
}
});
}
I wish to add a username or display name to it but am unable to do so. I tried a few things but still no result. Kindly help me. I need this functionality for a project submission this week.
This is definitely possibly but just not in the user creation method.
Once you've created your user (possibly in the addOnSuccessListener) you can use something similar to the following code to update the Users DisplayName:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setDisplayName("John Smith").build();
user.updateProfile(profileUpdates);
Hope this helps!
Edit: I previously said to add the code to the AuthStateListener, however, Frank's suggestion below to put it in the addOnSuccessListener is better/makes more sense so I have updated the answer to reflect this.
I just recently investigated this issue for my own implementation (SDK version 4.4.1). What I've found is that it works perfectly if you are sure to utilize the exact same task.result object from registration/login and not the object from the default instance.
Another work around that helped me is to have an email reference table in your FB DB like this:
{ "EmailRef": { "username1" : "email# domain .com"}, {"username2" : "email2#domain.com"} }
And then to query for the username by the user's email (from auth.CurrentUser.Email) using a method like this:
public static void GetCurrentUserName(Firebase.Auth.FirebaseUser user)
{
string message = "";
DatabaseReference dbRef = FbDbConnection();
FirebaseDatabase.DefaultInstance.GetReference("EmailRef").OrderByValue().EqualTo(user.Email).GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
message = "GetCurrentUserName encountered an error: " + task.Exception;
ModalManager.BuildFireBaseDebugModal(message);
Debug.LogError(message);
return;
}
if (task.IsCanceled)
{
message = "GetCurrentUserName was canceled.";
Debug.LogError(message);
return;
}
if (task.IsCompleted)
{
foreach (DataSnapshot ss in task.Result.Children.AsEnumerable())
{
try
{
if (ss.Value != null)
{
if (ss.Value.ToString() == user.Email)
{
message = "GetCurrentUserName was successful -- Email: " + user.Email + " Username: " + user.DisplayName;
Debug.LogError(message);
}
}
return;
}
catch (Exception ex)
{
message = "GetCurrentUserName Exception: " + ex;
Debug.LogError(message);
return;
}
}
}
});
}

Categories

Resources