且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在用户注册时获取Firebase云端函数中的访问令牌?

更新时间:2023-09-25 18:03:04

用户创建触发器无法做到这一点。
您有多个选项:


  1. 注册后,从客户端获取访问令牌并将其保存在实时数据库在指定用户可访问的位置下。然后,您可以为该位置设置云功能数据库触发器。当触发时,您将获得访问令牌,并对GitHub进行API调用,并获取数据并按照您的要求进行操作。

  2. 客户端。由于您在客户端(浏览器)注册后拥有访问令牌,因此需要对GitHub进行API调用,然后将配置文件数据保存在用户只能访问的数据库位置中。您可以添加一个云端函数来触发对该位置的更改,如果您需要运行额外的管理操作。 Firebase身份验证(4.0.0)现在会返回其他用户数据。检查: https://firebase.google.com/docs/reference /js/firebase.auth#.UserCredential
    您可以通过调用result.additionalUserInfo.profile或GitHub用户名:result.additionalUserInfo.username来获得附加数据。

    When a client signs in with Github, I would like to trigger a Cloud Function that retrieves the user's profile data from Github and stores it in /users/{uid}/profile in the Realtime database.

    I can trigger my cloud function when a new user signs up using:

    exports.fetchProfile = functions.auth.user().onCreate(event => {
      // user = event.data
      // uid = user.uid
      // access_token = ???
    
      // todo: request user profile from Github using access_token
      // todo: save profile in /users/{uid}/profile
    });
    

    But, how do I obtain the user's access_token needed for making the Github profile request? Thanks.

    What I have tried:

    1. On the client, use FirebaseAuth to get the Github access_token.
    2. Create a Firebase credential using the access_token from (1).
    3. Sign in with the credential from (2), I get a FIRUser in success callback, from which I can obtain uid.
    4. I write {uid: access_token} to a queue in the Realtime database, this in turn triggers my cloud function that does the profile retrieval.

    All these just to get the user's access_token, can I do better?

    You can't do it with the user creation trigger. You have multiple options:

    1. after sign up, get the access token from the client and saved it in the real-time database under a location accessible by the specified user. You can then set a cloud functions database trigger for that location. When that is triggered, you get the access token and make your API call to GitHub and get the data and do whatever you want with it.

    2. Run everything on the client side. Since you have the access token after sign up in the client (browser), make the API call to GitHub and then save the profile data in a database location accessible by the user only. You can add a cloud function to trigger on changes to that location if you need to run additional admin operations.

    By the way, Firebase Auth (4.0.0) now returns additional user data. Check: https://firebase.google.com/docs/reference/js/firebase.auth#.UserCredential You can get the additional data by calling result.additionalUserInfo.profile, or the GitHub username: result.additionalUserInfo.username.