从实时数据库获取数据后在云功能中创建自定义令牌

creating custom token in cloud function after reteiving data from realtime database

我想在云函数中创建自定义令牌,但在此之前我想检查和比较来自实时数据库的时间戳和当前 time.if 时间戳低于 10 分钟然后我想创建自定义令牌并发送回到 client.please 帮助我实现 this.i 我是这个云函数 firebase 的新手。

这是我的代码

export const authaccount = functions.https.onCall(async (data) => {
  try {
    const snap= await admin.database().ref("/register/"+data).get();
    const time=snap.val().timestamp;
    const now=new Date().getDate();
    const reg=new Date(time).getDate();
    const today=Math.abs(now-reg);
    const daydiff=Math.floor(today/1000/60/60/24);
    const nowminutes=new Date().getUTCMinutes();
    const regminutes=new Date(time).getUTCMinutes();
    const timediff=Math.abs(nowminutes-regminutes);
    if (timediff<10 && daydiff==0) {
      try {
        admin.auth().createCustomToken(data).then((customtoken)=>{
          console.log("auth created"+" "+timediff+" "+daydiff+" "+customtoken);
          return customtoken;
        });
      } catch (err1) {
        throw new functions.https.HttpsError("unknown", err1.message, err1);
      }
    } else {
      console.log("else "+" "+now+" "+reg+" "+time+" "+daydiff);
    }
  } catch (err2) {
    throw new functions.https.HttpsError("unknown", err2.message, err2);
  }
});
2:53:20.626 AM
authaccount
Error: Process exited with code 16 at process.<anonymous> (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:275:22) at process.emit (events.js:314:20) at process.EventEmitter.emit (domain.js:483:12) at process.exit (internal/process/per_thread.js:168:15) at Object.sendCrashResponse (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/logger.js:37:9) at process.<anonymous> (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:271:22) at process.emit (events.js:314:20) at process.EventEmitter.emit (domain.js:483:12) at processPromiseRejections (internal/process/promises.js:209:33) at processTicksAndRejections (internal/process/task_queues.js:98:32)
2:53:19.559 AM
authaccount
Error: The caller does not have permission; Please refer to https://firebase.google.com/docs/auth/admin/create-custom-tokens for more details on how to use and troubleshoot this feature. at FirebaseAuthError.FirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:44:28) at FirebaseAuthError.PrefixedFirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:90:28) at new FirebaseAuthError (/workspace/node_modules/firebase-admin/lib/utils/error.js:149:16) at Function.FirebaseAuthError.fromServerError (/workspace/node_modules/firebase-admin/lib/utils/error.js:188:16) at /workspace/node_modules/firebase-admin/lib/auth/token-generator.js:114:53 at processTicksAndRejections (internal/process/task_queues.js:97:5) at async Promise.all (index 1)
2:53:19.558 AM
authaccount
Unhandled rejection
2:53:19.469 AM
authaccount
Function execution took 1386 ms, finished with status code: 200

请帮忙解决这个问题。我不知道我在哪里犯了错误。

您需要确保您的 Firebase Admin sdk 已启动,并且 运行 在函数继续之前

if (firebase.apps.length === 0) {
    firebase.initializeApp();
}

资源:https://firebase.google.com/docs/admin/setup#initialize-without-parameters

我怀疑您是否修改了服务帐户的 IAM 权限,但正如评论所建议的那样:https://firebase.google.com/docs/auth/admin/create-custom-tokens#service_account_does_not_have_required_permissions

一旦确认有效 - 您将需要确保 onCall data 是一个字符串而不是 null,一些简单的健康检查可以帮助您调试您的流程

console.log(typeof data);
console.warn("Data", data);

从那里我还会调试你的日期时间和实时数据库结果,这些是异步的,需要在你使用它之前解决承诺。

更新:

所有云函数都应该return对客户端的响应 onCall 在客户端使用 promises 并支持 'return Object' 示例:

return {
  token: myCustomToken,
  possible: otherValue
};

为了比较,onRequest 使用类似 fetch 的响应并支持代码

response.status(500)
response.send({name:value})
return;

来源: https://firebase.google.com/docs/functions/callable#sending_back_the_result

来源: https://firebase.google.com/docs/functions/http-events#using_express_request_and_response_objects

更新:

所有路径和承诺都需要正确解决,这包括等待解决承诺和 return 处理它们的结果或存储结果以进行任何二次处理 - 我建议清理代码,删除 try/catch 并使用 .then().catch() 示例:

if (timediff<10 && daydiff==0) {
    return await admin.auth().createCustomToken(data)
        .then((customtoken)=>{
            console.log("auth created"+" "+timediff+" "+daydiff+" "+customtoken);
            return customtoken;
        })
        .catch (err) {
            return new functions.https.HttpsError("unknown", err.message, err);
         }
    } 
    else {
      console.log("else "+" "+now+" "+reg+" "+time+" "+daydiff);
    return "else "+" "+now+" "+reg+" "+time+" "+daydiff;
    }