问题
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:
- On the client, use FirebaseAuth to get the Github
access_token
. - Create a Firebase
credential
using theaccess_token
from (1). - Sign in with the
credential
from (2), I get aFIRUser
in success callback, from which I can obtainuid
. - 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:
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.
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