在不同的 firebase 云功能中重用身份验证逻辑

Reusing auth logic in different firebase cloud functions

我有这三个可调用函数,它们都在 运行 它们的主要逻辑之前进行身份验证检查。这看起来不是很干,我想知道是否有更聪明的方法来重用这个授权逻辑?

exports.addComment = functions.https.onCall(async (data, { auth }) => {
  if (auth) {
    //logic to add comment
  } else {
    throw new functions.https.HttpsError(
      "failed-precondition",
      "You must be authenticated"
    );
  }
});

exports.deleteComment = functions.https.onCall(async (data, { auth }) => {
  if (auth) {
    //logic to delete comment
  } else {
    throw new functions.https.HttpsError(
      "failed-precondition",
      "You must be authenticated"
    );
  }
});

exports.updateComment = functions.https.onCall(async (data, { auth }) => {
  if (auth) {
    //logic to update comment
  } else {
    throw new functions.https.HttpsError(
      "failed-precondition",
      "You must be authenticated"
    );
  }
});

我会在这里为你的场景使用装饰器。

基本上装饰器是一个函数,它接收一个函数并通过包装它来扩展它的功能。

所以它看起来像这样:

function authDecorator(functionWithLogic) {

   let innerFunc = () => {
      if (auth) {
      return functionWithLogic()
      } else {
      throw new functions.https.HttpsError(
        "failed-precondition",
        "You must be authenticated"
      );
    }
   return innerFunc

}

你也可以扩展它并根据需要传递相关参数给它