fetchPrimaryEmail sends an API request to retrieve the first verified primary email. 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://developer.atlassian.com/cloud/bitbucket/rest/api-
(token *oauth2.Token)
| 101 | // |
| 102 | // API reference: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-users/#api-user-emails-get |
| 103 | func (p *Bitbucket) fetchPrimaryEmail(token *oauth2.Token) (string, error) { |
| 104 | response, err := p.Client(token).Get(p.userInfoURL + "/emails") |
| 105 | if err != nil { |
| 106 | return "", err |
| 107 | } |
| 108 | defer response.Body.Close() |
| 109 | |
| 110 | // ignore common http errors caused by insufficient scope permissions |
| 111 | // (the email field is optional, aka. return the auth user without it) |
| 112 | if response.StatusCode >= 400 { |
| 113 | return "", nil |
| 114 | } |
| 115 | |
| 116 | data, err := io.ReadAll(response.Body) |
| 117 | if err != nil { |
| 118 | return "", err |
| 119 | } |
| 120 | |
| 121 | expected := struct { |
| 122 | Values []struct { |
| 123 | Email string `json:"email"` |
| 124 | IsPrimary bool `json:"is_primary"` |
| 125 | IsConfirmed bool `json:"is_confirmed"` |
| 126 | } `json:"values"` |
| 127 | }{} |
| 128 | if err := json.Unmarshal(data, &expected); err != nil { |
| 129 | return "", err |
| 130 | } |
| 131 | |
| 132 | for _, v := range expected.Values { |
| 133 | if v.IsPrimary && v.IsConfirmed { |
| 134 | return v.Email, nil |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | return "", nil |
| 139 | } |
no test coverage detected