This repository has been archived by the owner on Jan 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithubtoken.go
63 lines (49 loc) · 1.69 KB
/
githubtoken.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package travisci
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"github.com/pkg/errors"
)
type githubAuthRequest struct {
GitHubToken string `json:"github_token"`
}
type githubAuthResponse struct {
AccessToken string `json:"access_token"`
}
func travisTokenFromGitHubToken(githubAccessToken string, endpoint string) (string, error) {
requestBody := githubAuthRequest{GitHubToken: githubAccessToken}
url, err := url.Parse(endpoint)
if err != nil {
return "", errors.Wrapf(err, "parsing endpoint URL %v", endpoint)
}
url.Path = "/auth/github"
request, err := http.NewRequest("POST", url.String(), bytes.NewReader(mustJSONMarshal(requestBody)))
if err != nil {
return "", errors.Wrap(err, "creating request")
}
request.Header.Set("Content-Type", "application/json")
// Use a User-Agent that begins with "Travis" to avoid https://github.com/travis-ci/travis-ci/issues/5649
// This only seems to a be a problem at travis-ci.org (not .com)
request.Header.Set("User-Agent", "Travis-CI Go client")
response, err := http.DefaultClient.Do(request)
if err != nil {
return "", errors.Wrapf(err, "POST to %v", url.String())
}
defer response.Body.Close()
if response.StatusCode != 200 {
// Return full response body in error to allow for debugging.
responseBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
responseBytes = nil
}
return "", errors.Errorf(`"%s" from GitHub auth endpoint: %s`, response.Status, responseBytes)
}
var responseBody githubAuthResponse
if err := json.NewDecoder(response.Body).Decode(&responseBody); err != nil {
return "", errors.Wrapf(err, "parsing GitHub auth response as JSON")
}
return responseBody.AccessToken, nil
}