Switch between Users in FirebaseUser - FirebaseAuth - android

I've been working on an Admin Control panel on Android. inside which admin can add and disable the users.
Suppose the admin uid is I4YnygVk2eaCLEJbCiCLiWlo13as
mAuth.createUserWithEmailAndPassword(emailid, password)
.addOnCompleteListener(UserManagement.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful()+"uid"+mAuth.getCurrentUser().getUid());
//here the Uid is changed to the new registered user i.e RlhiQxMibWYA1NaqlN9JdFZ8ocK2.
AuthCredential credential = EmailAuthProvider
.getCredential("a#a.com", "123456");
firebaseUser.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//here what i need is getUid() should print the admin's uid(I4YnygVk2eaCLEJbCiCLiWlo13as), and not the newly created uid.
Log.d(TAG, "User re-authenticated."+firebaseUser.getUid()) database.getReference("users/"+mAuth.getCurrentUser().getUid()).child("active").setValue(true);
}
});
}
});

When your user creation is successful call this method
FirebaseAuth.getInstance().signOut();
this would signout the newly created user and then you can signin with admin credentials.

Related

How to replace autogenerated firebase node id to the current user email

I'm trying to replace autogenerated firebase node id to the current user email please check code below, I'm using firebase realtime database
Code:
mAuth.createUserWithEmailAndPassword(demail, dpass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(dname, demail, dcontact, dcity, dage);
FirebaseDatabase.getInstance().getReference("doctors")
.child("Doctors_Registration")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(signup.this, "Doctor Registered", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(signup.this, "Failed to Registered, Try Again!" + task.getException(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
The key of the node is determined by this code:
FirebaseDatabase.getInstance().getReference("doctors")
.child("Doctors_Registration")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) // 👈
.setValue(user)
So you're using the user's UID as the key for their node.
If you want to use the user's email you can use that instead of the UID. The only thing you'll need to take care of is to remove any . from the email address, as those are not a valid character in keys in the database.
So you could do:
FirebaseDatabase.getInstance().getReference("doctors")
.child("Doctors_Registration")
.child(email.replace(".", ",")) // 👈
.setValue(user)

How to delete a registered user by using firebase auth in android studio?

I have created the Register method using firebase authentication user register method.
How to delete a registered user by using firebase auth and android studio?
private void registerUser(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user successfully registered and logged in
Toast.makeText(MainActivity.this, "Registered Successfully",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
finish();
startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
}else{
Toast.makeText(MainActivity.this, "Could Not Register. Please Try Again Later",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
private void deleteUser(){
// TODO: Fill this method
}
You can use delete() method to remove the desired user from the Firebase. Please use this code:
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
AuthCredential authCredential = EmailAuthProvider.getCredential("user#example.com", "password1234");
firebaseUser.reauthenticate(authCredential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
firebaseUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted!");
}
}
});
}
});

Reauthenticate user x from an "admin user" to delete user x

In others Firebase version with removeUser we can delete an user only using email and password. With the new Firebase version it seems you can only delete and user if you have connected with that one... But the problem comes when I am connected with the admin user and I tried to delete the other user. This is the code.
final FirebaseUser user = mAuth.getCurrentUser();
AuthCredential credential = EmailAuthProvider
.getCredential(mail, postSnapshot.getValue(User.class).getPwdUser());
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener < Void > () {
#Override
public void onComplete(#NonNull Task < Void > task) {
user.delete().addOnCompleteListener(new OnCompleteListener < Void > () {
#Override
public void onComplete(#NonNull Task < Void > taskDeleted) {
if (taskDeleted.isSuccessful()) {
Toast.makeText(getApplicationContext(),
"Deleted user!", Toast.LENGTH_LONG).show();
}
}
});
}
});
But I can't get delete method because on reauthenticate it throws an error with "The supplied credentials do not correspond to the previously signed in user." Anyone knows how I can reauthenticate from another user?
The Firebase SDK for Android can only delete the currently logged in user. So if you know the user's email+password, you'll have to sign in as that user to delete the account.
For admin functionality you should use the Firebase Admin SDK, which you should run on a trusted back-end server. Authentication functionality currently is only available in the Firebase Admin SDK for Node.
Finally the code should be something like this
mAuth.signOut();
mAuth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(UserList.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
mAuth= FirebaseAuth.getInstance(myFirebaseRef.getDatabase().getApp());
try{
mAuth.signInWithEmailAndPassword(getsPreferences().getString("mailUser",""), getsPreferences().getString("pwd",""))
.addOnCompleteListener(UserList.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
}});
}catch(Exception e){
}
}
}});

Can we link auth providers without user login on Firebase for Android

I signed up with Google. Then I logged out and tried logging in using the same email address as Facebook. As I expected, the user has already registered the error. When I received the error, I gave it the credential to linkWithCredantials method that I got from Facebook. Of course I also got getCurrentUser null error here, because any user logged in. I don't get it well, when will I link auth providers? And my case I want to link auth providers with out login. Is it possible?
P.S.: Sorry for my English.
Here is my example :
private void handleFacebookAccessToken(final AccessToken token) {
Log.d(TAG_FACEBOOK, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
final AuthCredential linkCredential = credential;
mAuth.signInWithCredential(credential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG_FACEBOOK, "signInWithCredential:onComplete:" + task.isSuccessful());
if (task.isSuccessful()) {
replaceFragment(new ProfileFragment());
} else {
toast("Facebook authentication failed.");
}
}
}).addOnFailureListener(getActivity(), new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e.getMessage().contains("account already exists")) {
//**here**
mAuth.getCurrentUser().linkWithCredential(linkCredential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG_FACEBOOK, "linkWithCredential:onComplete:" + task.isSuccessful());
if (!task.isSuccessful()) {
}
}
});
}
}
});
}
To link two accounts, the user must sign in to both accounts. So they're already signed in as one of the accounts, which is then Firebase Authentication's currently signed in user. Then to link a different account to this, you provide the credentials for that account.

Firebase Authentication - How to delete user account using their emails?

Can I delete not authenticated user's account? The docs offers such a way:
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.");
}
}
});
Is this the only way to delete account?

Categories

Resources