Firebase Disable new user signup - java

I am currently using Firebase auth ui for signing in my users. What I want to achieve is to let only those users login who have created their account already.
I want Firebase auth ui to disable account sign-up whenever new credentials try to log in. Please tell me how to achieve this.
This is how I sign in my users:
if(FirebaseAuth.getInstance().getCurrentUser()==null) {
List<AuthUI.IdpConfig> idpConfigList = Arrays.asList(
//new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.PhoneBuilder().build()
);
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder()
.setAvailableProviders(idpConfigList).build(), SIGN_IN_CONST);
}else {
currentUser=FirebaseAuth.getInstance().getCurrentUser();
onSignedIn();
}
Thanks in advance.

What I want to achieve is to let only those users login who have created their account already.
It's the same thing if you want to check if a user is new. So to solve this, you can simply call AdditionalUserInfo's interface isNewUser() method:
Returns whether the user is new or existing
So please use the following lines of code:
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d(TAG, "Is New User!"); //Restrict the authentication process
} else {
Log.d(TAG, "Is Old User!"); //Allow user to authenticate
}
}
});

Related

How to check if email was already used in firebase? [duplicate]

I want to check when a user attempts to signup with createUserWithEmailAndPassword() in Firebase user Authentication method, this user is already registered with my app.
To detect whether a user with that email address already exists, you can detect when the call to createUserWithEmailAndPassword () fails with auth/email-already-in-use. I see that #Srinivasan just posted an answer for this.
Alternatively, you can detect that an email address is already used by calling fetchSignInMethodsForEmail().
The usual flow for this is that you first ask the user to enter their email address, then call fetchSignInMethodsForEmail, and then move them to a screen that either asks for the rest of their registration details (if they're new), or show them the provider(s) with which they're signed up already.
When the user trying to create an user with same email address, the task response will be "Response: The email address is already in use by another account."
mFirebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//User registered successfully
}else{
Log.i("Response","Failed to create user:"+task.getException().getMessage());
}
}
});
First of all, you need to make sure you have that restriction enabled in Firebase console (Account and email address settings). Take a look at #Srinivasan's answer.
Then, do this in your java code:
firebaseAuthenticator.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this, "User with this email already exist.", Toast.LENGTH_SHORT).show();
}
} else {
sendVerificationEmail();
startActivity(new Intent(SignUpActivity.this, DetailsCaptureActivity.class));
}
// ...
}
});
This is where the trick happens:
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this,
"User with this email already exist.", Toast.LENGTH_SHORT).show();
Several exceptions can be thrown when registering a user with email and password, but the one we are interested in is the FirebaseAuthUserCollisionException. As the name implies, this exception is thrown if the email already exists. If the exception thrown is an instance of this class, let the user know.
As a practice of #Frank's answer here is the code of using fetchProvidersForEmail()
private boolean checkAccountEmailExistInFirebase(String email) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final boolean[] b = new boolean[1];
mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
#Override
public void onComplete(#NonNull Task<ProviderQueryResult> task) {
b[0] = !task.getResult().getProviders().isEmpty();
}
});
return b[0];
}
I was looking into this kind of condition where we can detect if user exists or not and perform registration and login. fetchProvidersForEmail is best option right now. I have found this tutorial. Hope it helps you too!
See : Manage Users
UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmail(email);
System.out.println("Successfully fetched user data: " + userRecord.getEmail());
This method returns a UserRecord object for the user corresponding to the email provided.
If the provided email does not belong to an existing user or the user cannot be fetched for any other reason, the Admin SDK throws an error. For a full list of error codes, including descriptions and resolution steps, see Admin Authentication API Errors.
private ProgressDialog progressDialog;
progressDialog.setMessage("Registering, please Wait...");
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if (task.isSuccessful()) {
//Registration was successfull:
Toast.makeText(RegistrationActivity.this, "Successfully registered!", Toast.LENGTH_LONG).show();
} else {
//Registration failed:
//task.getException().getMessage() makes the magic
Toast.makeText(RegistrationActivity.this, "Registration failed! " + "\n" + task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
Add below code to MainActivity.java file.When user attempt to register with the same email address a message "The email address is already used by another account" will pop up as a Toast
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Sign up successfull", Toast.LENGTH_SHORT).show();
}
}
});
You do not have to do anything because the backend of Firebase will do the job.
Unless you are referring to reauthenticating of the app.
Take a scenario for an example, w

Firebase FirebaseAuth.getInstance().getCurrentUser().getDisplayName() returns null with a certain Gmail address

From the title, you would think that there is a published solution to my problem, but in fact I believe I read everything pertinent to my question, but nothing quite matched up. Here's what I've got:
First of all, this problem has never happened in my app before today, nor did my sign-in change in any way: same Google sign-in code, same account. Everything the same for the past three months, as long as I've been testing. And, as far as I can tell, the problem only occurs with a single account. When the user begins the sign-in process, they are presented with a choice of accounts to sign in with; in this case, I selected the first user:
Next, Google authenticates the user and we arrive here in the code:
So the question is, why did Firebase suddenly stop providing the display name (and the photo URL)? From the first screenshot, it's clear that the user has a specified name and photo. Apart from that, FirebaseAuth.getInstance().getCurrentUser().isAnonymous() is false, as expected. Any ideas on why this suddenly broke would be greatly appreciated!
I solved the problem by simply updating my name and photo URL using UserProfileChangeRequest() and the name and photo URL of my Google account, as suggested here:
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
sendFirebaseEvent(FIREBASE_GOOGLE_AUTH_EVENT, FIREBASE_GOOGLE_AUTH_KEY, acct.getId());
// [START_EXCLUDE silent]
showProgressDialog();
googleAccount = acct;
// [END_EXCLUDE]
final 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
sendFirebaseEvent(FIREBASE_GOOGLE_AUTH_EVENT, FIREBASE_GOOGLE_AUTH_RESULT_KEY, "Success");
launchNextActivity();
} else {
// If sign in fails, display a message to the user.
sendFirebaseEvent(FIREBASE_GOOGLE_AUTH_EVENT, FIREBASE_GOOGLE_AUTH_RESULT_KEY, task.getException().getMessage());
Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
updateUI(null);
}
// [START_EXCLUDE]
hideProgressDialog();
// [END_EXCLUDE]
}
});
}
private void launchNextActivity() {
mFirebaseAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mFirebaseAuth.getCurrentUser();
if (mUser.getDisplayName() == null || mUser.getDisplayName().length() == 0) {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(googleAccount.getDisplayName())
.setPhotoUri(googleAccount.getPhotoUrl())
.build();
mUser.updateProfile(profileUpdates);
}
}

validate existing user's mobile number in firebase

I have a firebase project which allows users to login only if they are already exists in identifier in authentication .
I already added few users using my web app with mobile numbers.
Now, in android I have used the signInWithPhoneAuthCredential method to get the users login.
But in this method, it allows any users to login even if the user is first time entering the mobile number.
Is there any method to restrict this ?
Sample Code :
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
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 = task.getResult().getUser();
// ...
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
}
}
}
});
}
According to the docs:
signInWithPhoneNumber:
Asynchronously signs in using a phone number. This method sends a code via SMS to the given phone number, and returns a firebase.auth.ConfirmationResult. After the user provides the code sent to their phone, call firebase.auth.ConfirmationResult.confirm with the code to sign the user in.
This is the default behavior in all applications that uses phone number as login. There is no method in the firebase docs that can restrict this.
you have to use firebase database also with this code to save user info, that way you can achieve your use case

How to get a user by Id and delete it after from firebase auth database

I want to add a feature in my app that allows the admin account to delete firebase user accounts from inside the app. I have the user Id that I want to delete stored in a String but can't get the user record from the firebase auth database using the Id.
The getUser() method stays in red and android studio shows a note :
Cannot resolve method getUser(java.lang.String).
I already tried searching on the net for previous similar problems but they were all trying to delete the connected user and not a specific user of a given ID
// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
final String UserId = myIntent.getStringExtra("uid"); // will return "User Id"
final Button btnDelete = findViewById(R.id.deleteaccount);
final FirebaseUser userToDelete = FirebaseAuth.getInstance().getUser(UserId);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userToDelete.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(TAG, "Account deleted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(TAG, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
})
}
});
I want to achieve one goal: Being able to delete a user with a given Id.
The Firebase web and mobile client libraries don't support the ability to get and delete user accounts, as that would pose a security risk. The only way to programmatically manage user accounts is using the Firebase Admin SDK to on a backend you control.

How to check if a user already exists in firebase during phone auth

I'm trying to create an app that only uses phone authorization from firebase. Since the login/signup is done through same process, which is verifying the sent code. How can i check if a user already exists in firebase? I need this to show them appropriate User Interface.
Right now, the only way to do that is via the Firebase Admin SDK. There is an API to lookup a user by phone number.
admin.auth().getUserByPhoneNumber(phoneNumber)
.then(function(userRecord) {
// User found.
})
.catch(function(error) {
console.log("Error fetching user data:", error);
});
You can check whether user already exist in Firebase by compare it metadata. see code example:
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, smsCode);
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(PhoneLoginEnterCodeActivity.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 = task.getResult().getUser();
long creationTimestamp = user.getMetadata().getCreationTimestamp();
long lastSignInTimestamp = user.getMetadata().getLastSignInTimestamp();
if (creationTimestamp == lastSignInTimestamp) {
//do create new user
} else {
//user is exists, just do login
}
} else {
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
}
}
}
});
There is an additionalUserInfo property that you can query like so (Kotlin):
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener {
it.result.additionalUserInfo?.isNewUser // new user check
}
If I borrow #Eltanan Derek code:
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, smsCode);
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(PhoneLoginEnterCodeActivity.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 = task.getResult().getUser().getAdditionalUserInfo();
if (user.isNewUser()) {
//do create new user
} else {
//user is exists, just do login
}
} else {
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
}
}
}
});

Categories

Resources