fetchVerifiedPrimaryEmail sends an API request to retrieve the verified primary email, in case "Keep my email address private" was set. NB! This method can succeed and still return an empty email. Error responses that are result of insufficient scopes permissions are ignored. API reference: https:
(token *oauth2.Token)
| 96 | // |
| 97 | // API reference: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user |
| 98 | func (p *Github) fetchVerifiedPrimaryEmail(token *oauth2.Token) (string, error) { |
| 99 | client := p.Client(token) |
| 100 | |
| 101 | response, err := client.Get(p.userInfoURL + "/emails") |
| 102 | if err != nil { |
| 103 | return "", err |
| 104 | } |
| 105 | defer response.Body.Close() |
| 106 | |
| 107 | // ignore common http errors caused by insufficient scope permissions |
| 108 | // (the email field is optional, aka. return the auth user without it) |
| 109 | if response.StatusCode == 401 || response.StatusCode == 403 || response.StatusCode == 404 { |
| 110 | return "", nil |
| 111 | } |
| 112 | |
| 113 | content, err := io.ReadAll(response.Body) |
| 114 | if err != nil { |
| 115 | return "", err |
| 116 | } |
| 117 | |
| 118 | emails := []struct { |
| 119 | Email string |
| 120 | Verified bool |
| 121 | Primary bool |
| 122 | }{} |
| 123 | if err := json.Unmarshal(content, &emails); err != nil { |
| 124 | return "", err |
| 125 | } |
| 126 | |
| 127 | // extract the verified primary email |
| 128 | for _, email := range emails { |
| 129 | if email.Verified && email.Primary { |
| 130 | return email.Email, nil |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | return "", nil |
| 135 | } |
no test coverage detected