How to obtain access token in Cloud Functions for Firebase when user signs up?

混江龙づ霸主 提交于 2019-12-11 04:44:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44148170/how-to-obtain-access-token-in-cloud-functions-for-firebase-when-user-signs-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!