从实时数据库检索数据后,在云函数中创建自定义令牌 [英] creating custom token in cloud function after reteiving data from realtime database

查看:95
本文介绍了从实时数据库检索数据后,在云函数中创建自定义令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在云函数中创建自定义令牌,但在此之前,我想检查实时数据库中的时间戳并将其与当前时间进行比较.如果时间戳小于10分钟,则我要创建自定义令牌并将其发送回客户端.请帮助我实现这一目标.我是这个云功能firebase的新手.

i want to create custom token in cloud function but before that I want to check and compare timestamp from realtime database and with current time.if the timestamp is below 10 min then I want to create custom token and send back to client.please help me to achieve this.i am new to this cloud function 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

请帮助解决此问题.我不知道我在哪里犯错.

please help to solve this problem. i don't know where I am making the mistake.

推荐答案

在功能继续运行之前,您需要确保Firebase Admin sdk已启动并正在运行

You will need to make sure your Firebase Admin sdk is initiated and running before the function proceeds

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

I doubt you have modified the IAM permissions on your service account but as the comment suggested: https://firebase.google.com/docs/auth/admin/create-custom-tokens#service_account_does_not_have_required_permissions

一旦确认可以正常工作-您需要确保onCall data 是字符串而不是null,一些简单的运行状况检查可以帮助您调试过程

Once that is confirmed to be working - you will need to ensure that the onCall data is a string and not null, some simple health checks can help you debug your process

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

从那里,我还将调试您的日期时间和实时数据库结果,这些都是异步的,需要先解决诺言,然后才能使用它.

from there I would also debug your date times and the realtime database result, these are async and will require the promise to be resolved before you can use it.

更新:

所有云功能应将响应返回给客户端onCall在客户端上使用诺言并支持返回对象"例如:

All cloud functions should return a response to the client onCall uses promises on the client and supports a 'return Object' example:

return {
  token: myCustomToken,
  possible: otherValue
};

为了进行比较,onRequest使用了类似获取的响应并支持代码

for comparison, onRequest uses fetch like responses and supports codes

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

更新:

所有路径和promise必须正确解析,这包括等待promise解析并返回其结果或将结果存储用于任何二次处理-我建议清理代码,删除 try/catch 并使用 .then().catch()示例:

all paths and promises need to resolve correctly, this includes awaiting promises to resolve and returning their result or storing the result for any secondary processing - I suggest cleaning up the code, remove the try/catch and use .then().catch() Example:

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;
    }

这篇关于从实时数据库检索数据后,在云函数中创建自定义令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆