Вопрос

I am developing a node.js app and recently figured out how to authenticate via GitHub. I want to know if there is a way to pull a user's profile photo and name so I can display it elsewhere in the app. I found this question, but it looks like Facebook and Google use different methods of obtaining these things.

Can someone point me in the right direction?

Это было полезно?

Решение

Passport module developers usually normalize the user profile object so some standard fields are available in the same way across all modules in this way:

  1. profile.id - assigned by the provider
  2. profile.username - their 'login'
  3. profile.displayName - full name of the user
  4. profile.profileUrl - user's profile page on the provider's site
  5. profile.emails - array of email addresses, but usually just a single address

Thus, you already have the username and/or displayname. One down!

These cover what is consistently needed, but providers can return other information. This naturally depends upon (a) what kind of services the provider offers and (b) the requested scopes.

The provider-specific info isn't lost. It is stored in profile._json next to the normalized properties...and inspecting this will show what else you have to work with.

For Github profile photos/images, you'll be looking for a gravatar_id property to get the user's photo URL.

You can confirm this, using the boilerplate example from passport-github for illustration purposes only, you could do something like this to see what Github is handing back to you so you can evaluate the entire provider response:

passport.use(new GitHubStrategy({
    // authentication stuff here, per `passport-github` docs
  },
  function(accessToken, refreshToken, profile, done) {
      // skipping error handling &c for brevity...
      fs.writeFile("githubProfile.json", JSON.stringify(profile));
      return done(null, profile);
    });
  }
));

If correct, you could then grab the user photo URL from profile._json.gravatar for use in whatever way you need (saving to database, inserting into a profile page, etc).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top