Check If an Email Exists Before Creating a User Firebase Android

Java Android Check if e-mail already exists on firebase

Firebase automatically tells you if an email that you want to create an account with already exists.
When creating an account you should check if the task was succesfull and under

if(task.isSuccessful()) {} // you have this code in your last bit of code
else{} // you have this in your code already

(

you currently have the code

Toast.makeText(getApplicationContext(), "registration not performed", Toast.LENGTH_SHORT).show();

( it is pretty much the last line in the code you provided) but you should replace it with:

try {
throw task.getException();
} catch(FirebaseAuthUserCollisionException e) {
// email already in use
Toast.makeText(getApplicationContext(), "Email already taken!", Toast.LENGTH_SHORT).show();
}

So you do not need to check if an email exists yourself because Firebase will automatically throw an exception and then you can for example display a toast.

How to check user email already exists in firebase using Android Studio

fetchProvidersForEmail is an async call so you have to make use of its return value with the callback.

return true on the main thread will not work.

Here is the solution :

First Create an interface with the method (success)

public interface OnEmailCheckListener(){
void onSuccess(boolean isRegistered);
}

Your checkEmail Method should be like this:

public void isCheckEmail(final String email,final OnEmailCheckListener listener){
mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>()
{
@Override
public void onComplete(@NonNull Task<ProviderQueryResult> task)
{
boolean check = !task.getResult().getProviders().isEmpty();

listener.onSuccess(check);

}
});

}

Finally call your isCheckEmail like this :

isCheckEmail("yourEmail@test.com",new OnEmailCheckListener(){
@Override
void onSuccess(boolean isRegistered){

if(isRegistered){
//The email was registered before
} else {
//The email not registered before
}

}
});

Hope this helps you.

How to check if email exists in firebase Auth

This probably isn't what you are looking for but what I usually do is store the users in a collection in firestore since that allows me to store multiple values for the user like nickname, picture, points etc. If you want some sample code on how to do this, let me know

EDIT

This is some code to help you get started.

First set up the firestore and set up a collection named users. Create a document in it with your mail id and add the fields you want for a user in it. If you do not do this you will get an error that the collection cannot be found or firestore is not set up

While signing up, do something like this given the email is in variable email and password in pass

FirebaseFirestore.instance.collection('users').doc(email).set((){
"email":email,
"pass":pass,
"nick":nick,//You can add more fields or remove them
});

When you want to check if the email exists, do something like

QuerySnapshot query = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo:email).get();
if (query.docs.length==0){
//Go to the sign up screen
}
else {
//Go to the login screen
}

Now to check the password while signing in, do something like

QuerySnapshot query = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo:email).get();//You can also pass this query as a parameter when you push the login screen to save some time
if (query.docs[0].get('pass')==pass){
//Go ahead login
}
else{
//Display an error message that password is wrong
}

If you want to store the data to automatically login when the user opens the app next time, look into the Shared Preference library.

If you want to pass the user data around, create a class called User()


class User {
String email;
String pass;
String nick;

User(this.email,this.nick,this.pass);
}

Then you can pass it around and easily manage the user data

is there any way to check an email id is present in firebase

You can use fetchSignInMethodsForEmail for this.

List<String> userSignInMethods = await auth.fetchSignInMethodsForEmail(email);

It will return an empty list when the email cannot be found.

How to check if user with the email entered by user on the login form exists or not in firebase

Since you commented on Mohammad's answer that the user isn't signed in yet, it its expected that your rules will reject the query. The obvious solution is to allow reads to everyone:

service cloud.firestore {
match /databases/{database}/documents {
match /users/{user} {
allow read;
allow write: if request.auth != null && user == request.auth.uid;
}
}
}

Note that this exposes your entire list of users to the world though, which may be a security risk.

You may want to limit what a user can query, by using the approach documented in securely querying data. To secure the query, you'd specify the list operation:

service cloud.firestore {
match /databases/{database}/documents {
match /users/{user} {
allow list: /* TODO: something to require a query on email address */;
allow read, write: if request.auth != null && user == request.auth.uid;
}
}
}

Note: I am still looking how to verify the query in the rules, since from the documentation it seems the where() condition is not exposed in request.query.

But this still runs the risk of exposing data of another user: if you know someone's email address, you can list their document, and thus get its data.

To prevent this, you have two options:

  1. Create a Cloud Function (or other server-side endpoint) that performs the query in a trusted environment, and only returns the true/false result to the user.
  2. Create a separate collection with just the user email addresses. In this collection I'd use the email addresses as the document ID, and then store the UID of the user as the (probably only) value in the document.

What you're trying to implement sounds quite close to Firebase Authentication's fetchSignInMethodsForEmail API, which lists the providers for a given email address. The idea of this API is that you combine it with the "only allow a single account per email address" setting, to implement a flow where on the first screen the user enters their email address, and then on a second screen you either allow them to register (the email address isn't known yet), or ask them for their credentials.

Check if an email already exists in Firebase Auth in Flutter App

The error raised is a PlatformException
so you can do something as follows-

try {
_firbaseAuth.createUserWithEmailAndPassword(
email: 'foo@bar.com',
password: 'password'
);
} catch(signUpError) {
if(signUpError is PlatformException) {
if(signUpError.code == 'ERROR_EMAIL_ALREADY_IN_USE') {
/// `foo@bar.com` has alread been registered.
}
}
}

The following error codes are reported by Firebase Auth -

  • ERROR_WEAK_PASSWORD - If the password is not strong enough.
  • ERROR_INVALID_EMAIL - If the email address is malformed.
  • ERROR_EMAIL_ALREADY_IN_USE - If the email is already in use by a different account.


Related Topics



Leave a reply



Submit