How to implement social login with GitHub so that I am able to get private emails of user for authentication if users email is set to private? Currently I am able to process user login when user email is public.
I know it has to be done somehow through https://api.github.com/user/emails but haven't been able to figure it out yet.
Current code for doing the social login through user public email:
package configs
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type GithubUser struct {
Email string `json:"email"`
Name string `json:"name"`
Avatar string `json:"avatar_url"`
}
func GetGithubAccessToken(code string) string {
clientID := GithubKey()
clientSecret := GithubSecret()
requestBodyMap := map[string]string{
"client_id": clientID,
"client_secret": clientSecret,
"code": code,
}
requestJSON, _ := json.Marshal(requestBodyMap)
req, reqerr := http.NewRequest("POST", "https://github.com/login/oauth/access_token", bytes.NewBuffer(requestJSON))
if reqerr != nil {
log.Panic("Request creation failed")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, resperr := http.DefaultClient.Do(req)
if resperr != nil {
log.Panic("Request failed")
}
respbody, _ := ioutil.ReadAll(resp.Body)
type githubAccessTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
}
var ghresp githubAccessTokenResponse
json.Unmarshal(respbody, &ghresp)
return ghresp.AccessToken
}
func GetGithubData(accessToken string) []byte {
req, reqerr := http.NewRequest("GET", "https://api.github.com/user", nil)
if reqerr != nil {
log.Panic("API Request creation failed")
}
authorizationHeaderValue := fmt.Sprintf("token %s", accessToken)
req.Header.Set("Authorization", authorizationHeaderValue)
resp, resperr := http.DefaultClient.Do(req)
if resperr != nil {
log.Panic("Request failed")
}
respbody, _ := ioutil.ReadAll(resp.Body)
return respbody
}