FirebaseAuthUserCollisionException? - android

I am using the firebase documentation to use Facebook login my android application. I am successfully able to login users using Google and Twitter. But when i click on Login with Facebook, the button is changing to Logout button. Actually it should redirect to Login success activity, because i configured FirebaseAuth.AuthStateListener.
I am posting the Activity here, Please let me know if i am doing anything wrong.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private static final int GOOGLE_RC_SIGN_IN = 9001;
private static final int TWITTER_RC_SIGN_IN = 140;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private GoogleApiClient mGoogleApiClient;
CallbackManager callbackManager;
#BindView(R.id.google_signin_button) SignInButton mGoogleSigninButton;
#BindView(R.id.facebook_login_button) LoginButton mFacebookLoginButton;
#BindView(R.id.twitter_login_button) TwitterLoginButton mTwitterLoginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(getString(R.string.twitter_consumer_key), getString(R.string.twitter_consumer_secret));
Fabric.with(this, new Twitter(authConfig));
FacebookSdk.sdkInitialize(this);
setContentView(R.layout.activity_main);
ButterKnife.bind(MainActivity.this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
.build();
mAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//User is signed in
Log.v(TAG, "Yo Baby");
Log.d(TAG,"name"+user.getDisplayName());
goToHome();
} else {
//Do some logic
}
}
};
mGoogleSigninButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signinIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signinIntent, GOOGLE_RC_SIGN_IN);
}
});
callbackManager = CallbackManager.Factory.create();
mFacebookLoginButton.setReadPermissions("email", "public_profile");
mFacebookLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAuthentication(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
mTwitterLoginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
handleTwitterAuthentication(result.data);
}
#Override
public void failure(TwitterException exception) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GOOGLE_RC_SIGN_IN){
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
handleGoogleAuthentication(account);
} else {
//Google Login Failed
}
} else if (requestCode == TWITTER_RC_SIGN_IN) {
mTwitterLoginButton.onActivityResult(requestCode,resultCode,data);
} else {
callbackManager.onActivityResult(requestCode,resultCode,data);
}
}
private void handleGoogleAuthentication(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Save Credentials in Google Smart Lock
} else {
//
}
}
});
}
private void handleFacebookAuthentication(AccessToken accessToken) {
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Save Credentials in Google Smart Lock
} else {
}
}
});
}
private void handleTwitterAuthentication(TwitterSession session) {
AuthCredential credential = TwitterAuthProvider.getCredential(session.getAuthToken().token, session.getAuthToken().secret);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Save credentials in Google Smart lock
} else {
}
}
});
}
private void goToHome() {
startActivity(new Intent(MainActivity.this, HomeActivity.class));
finish();
return;
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthStateListener != null) {
mAuth.removeAuthStateListener(mAuthStateListener);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Update1
Finally I understood the reason why Facebook login is not working. This is because i already logged into the app using Google Signin. Since my email for Google and Facebook are same it is giving FirebaseAuthUserCollisionException. I should have Debugged the application before i post the question in Stackoverflow.
Update2
I am not closing this question as it may help someone who faced the situation like me. And I will also update the solution for FirebaseAuthUserCollisionException, as i dig more into it.

I faced the same problem and this is how I got around with.
If the task is not successful, I'm checking whether the exception thrown is an instanceof FirebaseAuthUserCollisionException. If yes, a toast is displayed to the user saying 'Account with email already exists!'.
private void handleFacebookAccessToken(final AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(getApplicationContext(), "Firebase Facebook login failed",
Toast.LENGTH_SHORT).show();
if(task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "User with Email id already exists",
Toast.LENGTH_SHORT).show();
}
LoginManager.getInstance().logOut();
}
}
});
}
Credit: Check if given email exists

About FirebaseAuthUserCollisionException:
https://developers.google.com/android/reference/com/google/firebase/auth/FirebaseAuthUserCollisionException
Preventing users from creating multiple accounts using the same email address with different authentication providers.
see https://support.google.com/firebase/answer/6400716

Related

Google doesn't display the email menu

Hy, I'm trying to make a login on firebase using google SignIn. My problem is that when i'm gooing to connect, the application doesn't show me the email menu with all the email available and it do the connection without give the possibility to set more than one account.
I post my code below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn_Sign = (SignInButton) findViewById(R.id.sign);
mAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
GoogleSignInOptions SignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, SignInOptions).build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Btn_Sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent start = new Intent(MainActivity.this, Main2Activity.class);
startActivity(start);
} else {
Log.e(TAG, "signInWithCredential:failure", task.getException());
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
Thanks for the answers.
If you want to have always the dialog showing you need to disconnect your user before sign in
You can do it with this code
GoogleSignIn.getClient(getActivity(), GoogleSignInUser.getGoogleSignInOptions(getActivity())).signOut()
.addOnCompleteListener(getActivity(), new OnCompleteListener<Void>() {
#Override
public void onComplete(#android.support.annotation.NonNull Task<Void> task) {
GoogleSignIn.getClient(getActivity(), GoogleSignInUser.getGoogleSignInOptions(getActivity())).revokeAccess()
.addOnCompleteListener(getActivity(), new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//do what you want
}
})
.addOnCanceledListener(new OnCanceledListener() {
#Override
public void onCanceled() {
//do what you want
}
});
}
});

Fail firebase auth facebook

i'm trying to make an auth with facebook on firebase. I've already set up facebook SDK and I can sign in with facebook perfectly.
But I can't get firebase auth work. The app has a TOAST on the method onComplete(Task <AuthResult> task) and if something went wrong during the process it will show up. I'm getting this TOAST error, but can't find where is the problem. I've set up everything like in firebase docs.
public class LoginActivity extends AppCompatActivity {
private LoginButton loginButton;
private CallbackManager callbackManager;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.loginButton);
loginButton.setReadPermissions("email","public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(),"Error al iniciar sesión",Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(),"Error al iniciar sesión",Toast.LENGTH_LONG).show();
}
});
firebaseAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
goMainScreen();
}
}
};
}
private void handleFacebookAccessToken(AccessToken accessToken) {
Log.d("","handle"+accessToken.getCurrentAccessToken().getToken());
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getCurrentAccessToken().getToken());
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show(); // here is the ERROR.
}
}
});
}
private void goMainScreen() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(firebaseAuthListener);
}
}
I've already enabled Facebook auth on firebase and already copied the id and secret. Also I've already copied the Firebase URL in Facebook developers.
The task contains error information that may help you troubleshoot. Instead of showing "error" in your toast, show task.getException().toString() or better yet: throw the exception with throw task.getException().

Firebase facebook and google login error in android

Here is my error screenshotHello I am trying to login with Google and Facebook but it gives error.
com.google.firebase.auth.FirebaseAuthException: This operation is not allowed. You must enable this service in the console. How to solve this error? Do I have also enable the services on firebase how to solve this problem?
here is my code
public class LoginActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
private Button btn_sign_up_login, btn_login, btn_gmail_login, btn_facebook_login;
private ProgressBar pb_sign_up_login, pb_login;
private FirebaseAuth.AuthStateListener mAuththenticatelistner;
private GoogleApiClient mGoogleapiclient;
public static final int RC_GOOGLE_LOGIN = 1;
private FirebaseAuth mAuth;
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_sign_up_login = (Button) findViewById(R.id.btn_sign_up_login);
callbackManager = CallbackManager.Factory.create();
btn_login = (Button) findViewById(R.id.btn_login);
btn_gmail_login = (Button) findViewById(R.id.btn_gmail_login);
btn_facebook_login = (Button) findViewById(R.id.btn_facebook_login);
pb_login = (ProgressBar) findViewById(R.id.pb_login);
///////////////////////////code for facebook login
// Initialize Facebook Login button
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.btn_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessTokens(loginResult.getAccessToken());
}
#Override
public void onCancel() {
// [START_EXCLUDE]
updateUI(null);
// [END_EXCLUDE]
}
#Override
public void onError(FacebookException error) {
// [START_EXCLUDE]
updateUI(null);
// [END_EXCLUDE]
}
});
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.web_api_client_id))
.requestEmail()
.build();
mGoogleapiclient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mAuth = FirebaseAuth.getInstance();
btn_sign_up_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
}
});
btn_gmail_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
btn_facebook_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleapiclient);
startActivityForResult(signInIntent, RC_GOOGLE_LOGIN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_GOOGLE_LOGIN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}
// [START auth_with_google]
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), 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
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
startActivity(new Intent(LoginActivity.this, DrawerActivity.class));
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}
#Override
public void onClick(View view) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
private void updateUI(FirebaseUser user) {
if (user != null) {
String mailid = (getString(R.string.google_status_fmt, user.getEmail()));
String idfor = (getString(R.string.firebase_status_fmt, user.getUid()));
} else {
}
}
// [START auth_with_facebook]
private void handleFacebookAccessTokens(AccessToken token) {
// [END_EXCLUDE]
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
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
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// [START_EXCLUDE]
// [END_EXCLUDE]
}
});
}
// [END auth_with_facebook]
}
As the error states, you need to enable the authentication methods in the Firebase console. Navigate to Authentication>Sign-In Method and enable the required methods.

How to automate login to Google OAuth to access known user account

I am using google firebase oAuth in my app for login
My problem is that everytime i open the app it ask to login .
I want to automate using token service but i dont know how to and what to do.
private static int RC_SIGN_IN = 0 ;
private static String TAG = "LOGIN_ACTIVITY";
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
Context context = LoginActivity.this;
public FirebaseAuth.AuthStateListener mAuthListener;
private EditText mEmailField,mPasswordField;
TextView register;
private String Email ;
Model_userDetails model_userDetails = new Model_userDetails(); ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
register = (TextView) findViewById(R.id.register);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null) {
// new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d("AUTH","User logged out");
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.email_sign_in_button).setOnClickListener(this);
mEmailField = (EditText) findViewById(R.id.email);
mPasswordField = (EditText) findViewById(R.id.password);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this,NewUserActivity.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener !=null)
mAuth.removeAuthStateListener(mAuthListener);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==RC_SIGN_IN)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess())
{
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
Email = mAuth.getCurrentUser().getEmail();
new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d(TAG,"Google login failed ");
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct){
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("AUTH","sign in with credentials: complete "+ task.isSuccessful());
}
});
}
private void signIn()
{
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent,RC_SIGN_IN);
}
private void emailSignIn()
{
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(email)|| TextUtils.isEmpty(password))
{
Toast.makeText(LoginActivity.this,"Fields are empty ",Toast.LENGTH_SHORT).show();
}
else
{
final ProgressDialog progressDialog = ProgressDialog.show(LoginActivity.this, "Please wait...", "Proccessing...", true);
(mAuth.signInWithEmailAndPassword(email,password))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent i = new Intent(LoginActivity.this, AccountActivity.class);
i.putExtra("Email", mAuth.getCurrentUser().getEmail());
startActivity(i);
} else {
Log.e("ERROR", task.getException().toString());
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG," Connection Failed");
}
This is my code
please help me with this
i got it myself . We have to call the new activity when checking if the user is login or not.
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null) {
new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d("AUTH","User logged out");
}
};

Android Firebase Facebook Authentication Logout function

I am using the facebook auth medthod with firebase and I can't figure out how to properly Log out a user. After I press the 'Continue with Facebook' button and give it access to my profile the button changes in 'Log out' and shows a dialog when I click it. The problem is that it doesn't actually log me out and the state is still signed in.
I found here how to log out the user from Firebase and Facebook in my app but I can't figure out where to put those 2 lines. I am looking for a Logout function or something like that.
I found here (different here) what might be my solution but it's pretty messy and can't understand. Can you please help me?
#Override
protected void onCreate(Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.e(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "facebook:onError", error);
// ...
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.e(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
boolean userExists = false;
User userFirebase;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot mydata : dataSnapshot.getChildren()){
userFirebase = mydata.getValue(User.class);
if(userFirebase.getEmail().equals(user.getEmail())){
Log.e(TAG, "User found in the database");
userExists = true;
Intent intent = new Intent(getBaseContext(), ActivityMain.class);
startActivity(intent);
break;
}
}
if (!userExists){
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").push().setValue(new User(user.getDisplayName(),user.getEmail(),0,0));
Intent intent = new Intent(getBaseContext(), ActivityMain.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); // checks if the user is in database and writes him if not
} else {
// User is signed out
Log.e(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.e(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.e(TAG, "signInWithCredential: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.e(TAG, "signInWithCredential", task.getException());
Toast.makeText(getBaseContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
You need to implement your own button and add and OnClickListener with the 2 methods mentioned :
Button logoutButton = (Button) findViewById(R.id.logout_button);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
}
});
You can't use the facebook logout button , because it only logs you out of facebook and you need the firebase logout aswell.

Categories

Resources