1

In my app, I would like to check if there is a document with the same email before a user signs in (where 'email' is a field of documents in my 'user_data' collections)...

I already did the code which does that, but it needs access to my Firestore database even though the user isn't already signed in (and in my Firestore rules I said allow read, write: if request.auth != null;)

So, how can I change my Firestore rules without allowing read to everyone?

2 Answers 2

1

I think changing your firebase database security rules to the public is not advisable.

But I could understand your situation. I could give you an idea.

This is how I implement it, without changing the security rules.

WHEN YOU WANT TO CHECK AFTER CLICKING THE BUTTON:

//SIGN UP

try {
  UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
    email: "USER ENTERED PASSWORD",
    password: "SuperSecretPassword!"
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'email-already-in-use') {
    print('The account already exists for that email.');
    // Tell User That It already exists!
  }
} catch (e) {
  print(e);
}

// Or SIGN IN

try {
 UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: "[email protected]",
    password: "SuperSecretPassword!"
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'user-not-found') {
    print('No user found for that email.');
  } else if (e.code == 'wrong-password') {
    print('Wrong password provided for that user.');
  }
}

WHEN YOU WANT TO CHECK WHILE TYPING IN EMAIL TEXTFIELD:

UserCredential userCredential = await FirebaseAuth.instance.signInAnonymously();

You could sign in anonymously and read the database! After reading and filtering out log out the user.

Or else if you haven't convinced yet, then here you go,

Refer: https://firebase.google.com/docs/rules/basics#content-owner_only_access

Make read to public and write to auth users.

Hope that suits your case!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was using both email/password and Google login so I couldn't use the email already in use exception, but I solved with the anonymous login one :)
1

change

allow read, write: if request.auth != null;

to

allow read, write: if true;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.