创建具有特定 ID 方案的用户时如何处理 Firestone 规则?

How to handle Firestone rules when creating a user with a specific ID scheme?

我正在创建一个签入应用程序,其中每个签入的用户都会从以下方案中获取特定的 uid:

  const generateUid = (fetched_id) => {
    let x = fetched_id.substr(0, 1);
    let y = fetched_id.substr(1, 4);
    if (y < 9999) {
      y++;
    } else {
      y = 1;
      x = String.fromCharCode(x.charCodeAt(0) + 1);
    }
    return `${x}${String(y).padStart(4, "0")}`;
  };

我正在使用以下逻辑生成用户:

const generateUser = () => {
    setLoading(true);
    firebase
      .auth()
      .signInAnonymously()
      .then((loggedInUser) => {
        database
          .collection("users")
          .orderBy("uid", "desc")
          .limit(1)
          .get()
          .then((snapshot) => {
            snapshot.forEach((fetchedUser) => {
              const newUid = generateUid(fetchedUser.id);
              database
                .collection("users")
                .doc(newUid)
                .set({
                  name: user.name,
                  mail: user.mail,
                  tel: user.tel,
                  street: user.street,
                  zip: user.zip,
                  city: user.city,
                  date_checkin: firebase.firestore.Timestamp.fromDate(
                    new Date()
                  ),
                  uid: newUid,
                  userId: loggedInUser.user.uid,
                })
                .then(() => {
                  setLoading(false);
                  history.push(`${folderPath}/checkedin/${newUid}-${uniqueId}`);
                })
                .catch((error) => {
                  console.log(error);
                  setLoading(false);
                });
            });
          })
          .catch((error) => {
            console.log(error);
            setLoading(false);
          });
      })
      .catch((error) => {
        console.log(error);
        setLoading(false);
      });
  };

由于我对 Firestone 规则还很陌生,我想知道如何处理读写访问。 我看到的问题以及我寻求解决方案的地方是:

您需要将最后生成的 ID 作为单个值存储在数据库中所有用户都可以读取和写入的已知路径中,比如值 lastGeneratedID

您需要为此值编写安全规则以确保 lastGeneratedID 写入始终按顺序进行并遵循您的命名方案。

您需要在客户端 reading/writing 为 lastGeneratedID 值时使用事务,以确保客户端在发生并发冲突更新时自动重试。