How to handle Github authentication in nodejs for users with null email?

Viewed 94

I have the regular authentication flow where the user registers with a password and email and would like to add Github authentication but I noticed that the email field can come up with null if the user doesn't add it to their profile. I would like to know the best approach to saving users registered with Github on the backend

1 Answers

Github's oAuth documentation doesn't lists the scope parameter that you can supply while get user code. Plus, you can't get it though the /user endpoint, you need to make an extra request to user/emails

  1. To get the "Code", first redirect the user to https://github.com/login/oauth/authorize?client_id={CLIENTID}&redirect_uri={REDIRECT_URL}&scope=read:user,user:email

  2. Then to get the Access Token, make a POST request with the "Code" you received, like so: https://github.com/login/oauth/access_token?client_id={clientID}&client_secret={clientSecret}&code={code}

  3. Now when you when you receive the access token, first make a request to the /user endpoint, and then make a request to the /user/emails endpoint. Make sure you pass the access token in the header with parameter Authorization: "token {accessToken}"

To get the basic user data make a GET request to this url: https://api.github.com/user

And then to get the user emails, make a GET request to https://api.github.com/user/emails

You may get multiple emails in your result. The result will look something like this:

[
  {
    email: 'johndoe100@gmail.com',
    primary: true,
    verified: true,
    visibility: 'public'
  },
  {
    email: 'johndoe111@domain.com',
    primary: false,
    verified: true,
    visibility: null
  }
]

You can select the one that has the primary parameter set to true.

Related