0

I am trying to get a document from firestore before any user is logged in. This is used in the register function of my app in order to delete any unverified user accounts using the same email. I know I could use a cron job to do this but I prefer having it in the actual app itself for simplicity. This is the code that I am using:


  const auth = getAuth(app);
  await getDoc(doc(db, "Users", email)).then(async (snap) => {
  if (snap.exists()) {
  const expired = moment(moment().format()).diff(
     snap.data().CreationDate,
        "minute"
   );
      if (expired > 2880 && snap.data().Verified == false) {
     await deleteDoc(doc(db, "Users", email));
       deleteUser(userCredential.user);
       }
     }
   });
  await createUserWithEmailAndPassword(auth, email, password)
    .then(async (userCredential) => {
      const user = userCredential.user;
      sendEmailVerification(user);
      await setDoc(doc(db, "Users", userCredential.user.email), {
        Email: userCredential.user.email,
        CreationDate: moment().format(),
        Verified: false,
      });
      c_setEmail(email);
      auth.updateCurrentUser(userCredential.user);
      navigation.replace("AuthVerify");
    })
    .catch((error) => {
      // CATCH
    });

Current security rules:


rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

Error that I get when getDoc() is called:


    Possible Unhandled Promise Rejection (id: 0):
    FirebaseError: Missing or insufficient permissions.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
hrodric
  • 390
  • 2
  • 12
  • It sounds like you want `if true`? – Frank van Puffelen Sep 23 '22 at 03:10
  • Yes but that is like turning off security, I wanted a way to allow the unauthenticated user to only access a specific value of the user document, I've read the docs but I don't think there's any way to add a security rule to only one field? – hrodric Sep 23 '22 at 13:01

1 Answers1

0

If the user isn't logged in yet, you can't make any checks based on their identity in the security rules.

Security rules can only allow or deny access to a complete document. There is no way to allow a user to only read a part of a document in security rules.

You can let them sign-in first, and then allow the user to overwrite any user doc that claims the same email address. You'll probably also want to look at these documents on enforcing uniqueness, as that can only be guaranteed if you use the unique value as the document ID:

If you don't want to change the structure, periodic cleanup (e.g. in a Cloud Function) is probably a good idea indeed. Also consider running the entire unique claim of an email address in a Cloud Functions, as it'll be easier to enforce there (as you can be certain that all code running is code that you wrote).

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807