首页 > 解决方案 > Cloud Functions:检查 Firestore 中的用户文档中是否存在电子邮件不起作用

问题描述

我有一个向用户添加管理员权限的云功能。我让它工作了,但是当我尝试添加一层错误处理时(这样当传入不是注册用户的电子邮件时不会发生异常)我没有让它工作,并且在刮擦之后我的头好几个小时我仍然无法弄清楚。

发生的事情是这段代码总是 return null,我认为这可能与checkIfUserWithEmailExists is never turn 的结果有关true

这是我创建的代码:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

exports.addAdmin = functions.https.onCall(async (data, context) => {
  const result = await checkIfUserWithEmailExists(data.email);
  if (result === true) {
    if (context.auth.token.admin !== true) {
      return {
        error: "Request not authorized. User must be an admin to fulfill"
      };
    }
    const email_1 = data.email;
    return grantAdminRole(email_1).then(() => {
      return {
        result: `Request fulfilled! ${email_1} is now an admin`
      };
    });
  } else {
    return {
      error: "No user with this email was found"
    };
  }
});

async function grantAdminRole(email_2) {
  // get user and add custom claim (admin)
  const user = await admin.auth().getUserByEmail(email_2);
  if (user.customClaims && user.customClaims.admin === true) {
    return;
  }
  return admin.auth().setCustomUserClaims(user.uid, {
    admin: true
  });
}

//Checks that the email passed in is an existing user
async function checkIfUserWithEmailExists(email) {
  const userCollectionRef = admin.firestore().collection("users");
  userCollectionRef
    .where("email", "==", email)
    .get()
    .then(querySnapshot => {
      if (querySnapshot.size === 1) {
        return true;
      } else {
        return false;
      }
    });
}

标签: javascriptfirebasegoogle-cloud-firestorefirebase-authenticationgoogle-cloud-functions

解决方案


您没有正确等待检查功能中的承诺。尝试这个:

//Checks that the email passed in is an existing user
async function checkIfUserWithEmailExists(email) {
  const userCollectionRef = admin.firestore().collection("users");
  const querySnapshot = await userCollectionRef
    .where("email", "==", email)
    .get();

  return querySnapshot.size >= 1;
}

一般来说,将 async/await 与 Promise 结合起来可能会让人感到困惑,.then()所以我尽量避免这样做。


推荐阅读