passport-github2 returns null in email field

418 Views Asked by At

passport-github2 returns null in email field even when {scope: ['user:email']} was passed to passport.authenticate('github', {scope: ['user:email'] , session: false})(req, res, next)

1

There are 1 best solutions below

0
On

Upon looking a bit into the source code, I found that there exists a function to get the email of user but for that, we need to pass the scope where we initialize our GitHubStrategy. I'm not sure why it's not documented anywhere! To get it up and working I found that we need to do the following thing:

passport.use(new GitHubStrategy({
      clientID: GITHUB_OAUTH_CLIENT_ID,
      clientSecret: GITHUB_OAUTH_CLIENT_SECRET,
      callbackURL: GITHUB_OAUTH_CALLBACK,
      proxy: true,
      scope: ['user:email'] //This is all it takes to get emails
    }, (accessToken, refreshToken, profile, next) => {


// You get the profile object with emails array which can be accessed with 
// profile.emails[n].value

    }));

//middleware
passport.authenticate('github',  {scope: ['user:email']  , session: false})(req, res, next)

It's really weird that it's not documented in their repo.

Note: Since for GitHub, you can't get the email address directly if it's set to private by the user, you need to call another endpoint(docs). It's written over here inside the source code: (source)

PS: I'm still looking for a better way to access email without passing scope at two places.