How to getDoc() without a signed user

Viewed 29

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.

1 Answers

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).

Related