I am using Firebase Auth with the Facebook & Google login. After a successful login, I also register the user on my own server.
// facebook or google auth
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
registerOnServer(task);
}
});
That works fine the first time. But the second time the user logs in, my backend complains, because a user with those credentials already exists.
How can I detect if this is the first time a user logs in via one of the given providers? I can't use SharedPreferes, because they get erased after a user uninstalls the app, which leads to problems after reinstalling.
firebaseAuth.fetchProvidersForEmail(userEmail).
addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
#Override
public void onComplete(#NonNull Task<ProviderQueryResult> task) {
List<String> providerList = task.getResult().getProviders();
if (providerList.isEmpty()) {
//Empty List means new user
}
else if (providerList.contains("facebook.com")) {
//Facebook is the provider
}
}
}
Use above code to get providers.
Related
I am making an app where if I delete users from the console user still can access some information from the database. so I reload the user every time users open the apps on the splash screen.
My concern is if it is a good idea or not to reload user every time opening the apps?
this is my current code is,
void reloadUserInfo() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
user.reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
goToHome();
} else {
Helper.customToast(Splash.this, task.getException().getMessage());
goToLogin();
}
}
});
else
goToLogin();
}
I don't see that there is a problem here. If you're observing a specific issue, please post a question that describes what's not working the way you expect.
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?
I started getting a FirebaseAuthUserCollisionException exception when I try to sign in with Facebook in my Android application.
com.google.firebase.auth.FirebaseAuthUserCollisionException: An
account already exists with the same email address but different
sign-in credentials. Sign in using a provider associated with this
email address.
I am using Firebase to handle the registration and Facebook to deliver a "one-click" login method, using a com.facebook.login.widget.LoginButton view as a trigger.
These sign-in method was already working. I was able to register a account with Facebook, and use the same method to log-in this account. But now have start to throwing this exception.
Here is the code where I register a account from Facebook and proceed with login:
private void handleFacebookAccessToken(AccessToken token) {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.show(getString(R.string.dialog_wait));
firebaseAuth.signInWithCredential(FacebookAuthProvider.getCredential(token.getToken()))
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#SuppressWarnings("ThrowableResultOfMethodCallIgnored")
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
dialog.close();
registerNewUserFromSocialLogin(firebaseAuth.getCurrentUser());
} else {
if(task.getException() instanceof FirebaseAuthUserCollisionException) {
//TODO: handle sign-in with different credentials
} else {
dialog.close();
LoginManager.getInstance().logOut();
Toast.makeText(LoginActivity.this,
R.string.error_login,
Toast.LENGTH_SHORT).show();
}
}
}
});
}
And my Gradle file with current use library:
compile 'com.google.firebase:firebase-auth:10.2.1'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
So my problem is: I don't know how to handle FirebaseAuthUserCollisionException exception.
None of the solutions in StackOverflow or Firebase Documentation help me. I am looking for a solution that is able to login the user although the duplicated credential, to stil deliver the "one-click" login method.
You will get that error when the user had previously signed in with the same email using a different provider. For example, the user signs in with email user#gmail.com using Google. The user then tries to sign in with the same email but using Facebook. The Firebase Auth backend will return that error (account exists with different credential). In that case, you should use the fetchProvidersForEmail to look up the existing providers associated with email user#gmail.com, in this case google.com. You signInWithCredential to the existing google account to prove ownership of that account, and then linkWithCredential the Facebook credential the user originally was trying to sign in with. This merges both accounts so in the future the user can sign in with either.
This happens when you use the single accounts per email. If you want to allow different accounts per email, you can switch to multiple accounts per email in the Firebase console.
Here is an example:
mAuth.signInWithCredential(authCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// Account exists with different credential. Assume the developer wants to
// continue and link new credential to existing account.
if (!task.isSuccessful() &&
task.getException() instanceof FirebaseAuthUserCollisionException) {
FirebaseAuthUserCollisionException exception =
(FirebaseAuthUserCollisionException)task.getException();
if (exception.getErrorCode() ==
ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL) {
// Lookup existing account’s provider ID.
mAuth.fetchProvidersForEmail(existingAcctEmail)
.addOnCompleteListener(new OnCompleteListener<ProviderQueryResult> {
#Override
public void onComplete(#NonNull Task<ProviderQueryResult> task) {
if (task.isSuccessful()) {
if (task.getResult().getProviders().contains(
EmailAuthProvider.PROVIDER_ID)) {
// Password account already exists with the same email.
// Ask user to provide password associated with that account.
...
// Sign in with email and the provided password.
// If this was a Google account, call signInWithCredential instead.
mAuth.signInWithEmailAndPassword(existingAcctEmail, password)
addOnCompleteListener(new OnCompleteListener<AuthResult> {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Link initial credential to existing account.
mAuth.getCurrentUser().linkWithCredential(authCredential);
}
}
});
}
}
}
});
}
}
});
There is no need for this, you can just allow multiple accounts merge under firebaase->authentication-> sign in method -> Advanced - > change (multiple accounts per email address.
Firebase will merge the same email address but will give you different user UID.
See sample below.
AuthCredential authCredential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(authCredential)
.addOnCompleteListener(this, 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();
LoginFacebookGoogleActivity.this.updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
if(task.getException() instanceof FirebaseAuthUserCollisionException){
FirebaseAuthUserCollisionException exception = (FirebaseAuthUserCollisionException) task.getException();
//log this bundle into the analytics to analyze which details you want to collect
}
Toast.makeText(LoginFacebookGoogleActivity.this, "Authentication failed " + task.getException(), Toast.LENGTH_SHORT).show();
LoginFacebookGoogleActivity.this.updateUI(null);
}
});
When I am trying to sign up a user using Firebase authentication method in my Android application, this is happening:
It's not registering a user
This is the Registration code
final String _name = txtName.getText().toString().trim();
String _email = txtEmail.getText().toString().trim();
String _pass = txtPass.getText().toString().trim();
if(!TextUtils.isEmpty(_name) && !TextUtils.isEmpty(_email) && !TextUtils.isEmpty(_pass) ) {
mProgress.setMessage("Registrando ...");
mProgress.show();
firAuth.createUserWithEmailAndPassword(_email, _pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
//the user has been registered
}
}
});
You are registring the user but not hiding the progress bar after user successfully registered in the firebase. Try applying this code and check the firebase dashboard for authentication. And also Implement onFailureListener to know the reason why user is not being registered.
firAuth.createUserWithEmailAndPassword(_email, _pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mProgress.dismis();
if(task.isSuccessful()) {
//the user has been registered
Log.d("onSuccess","USER REGISTERED");
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
mProgress.dismis();
Log.e("onFailure",e.getMessage());
}
}
);
EDIT: If you are still facing the same issue go and check these settings in your firebase console authentication tab ,
Select SIGN-IN METHOD and Check the status of Email/Password if it is Disable then switch it to the Enable.
And it looks like you are using Genymotion, so have you installed the Google Libraries into your virtual device ?
If not follow this thread or test your app on a physical device
I referenced the documentation in Firebase page. My problem is in this paragraph:
The call to linkWithCredential will fail if the credentials are already linked to another user account. In this situation, you must handle merging the accounts and associated data as appropriate for your app:
FirebaseUser prevUser = currentUser; currentUser = auth.signInWithCredential(credential).await().getUser(); // Merge
prevUser and currentUser accounts and data // ...
I can't figure out how to add this code into my project. When and where do I put this code
auth.signInWithCredential(credential).await().getUser();
into my java file? Android Studio announced me that it can't resolve await() method.
What should I do to resolve that problem. Thank you in advance!
You should handle this part of code when the linkWithCredentials call fails.
Here is a small example :
mAuth.getCurrentUser().linkWithCredential(credentials).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
FirebaseUser prevUser = currentUser;
try {
currentUser = Tasks.await(auth.signInWithCredential(credential)).getUser();
} catch (Exception e) {
e.printStackStrace();
}
// Merge prevUser and currentUser accounts and data
// ...
} else {
}
}
});
NB: Task.await() doesn't exist anymore you should use Tasks.await(...) static method instead.
Suppose that:
One account per email address setting is enabled on firebase authentication
User are logging in with anonymous authentication
The linkWithCredential usually fails with FirebaseAuthUserCollisionException, it could happen either because this credential is used to login before (you can check by searching this email on firebase console) or this email account is used to login before but with different providers ( such as a user logged in with abc#gmail.com by using google sign in before, now he/she uses abc#gmail.com but with Facebook login ) To handle it, you need 2 steps:
Step 1: link with anonymous account
private void linkWithAnonymousAccount(final AuthCredential credential) {
mFirebaseAuth.getCurrentUser().linkWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
getFirebaseToken();
} else {
Exception exception = task.getException();
if (exception instanceof FirebaseAuthUserCollisionException) {
signInWithFirebase(credential);
} else {
Utils.showDialogMessage(mContext, task.getException().getLocalizedMessage());
}
}
}
});
}
Step 2: sign with firebase
private void signInWithFirebase(AuthCredential credential) {
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
getFirebaseToken();
} else {
Utils.showDialogMessage(mContext, task.getException().getLocalizedMessage());
}
}
});
}
Google says the step 2 is merging because after signed in, you need to get information of the previous user and put into the new user.
I hope it helpful.