1// Copyright (c) 2015 Ableton AG, Berlin. All rights reserved. 2// 3// Use of this source code is governed by a BSD-style 4// license that can be found in the LICENSE file. 5 6package travis 7 8import ( 9 "context" 10 "fmt" 11 "net/http" 12) 13 14// BuildsService handles communication with the builds 15// related methods of the Travis CI API. 16type AuthenticationService struct { 17 client *Client 18} 19 20// AccessToken is a token to access Travis CI API 21type AccessToken string 22 23type accessTokenResponse struct { 24 Token AccessToken `json:"access_token"` 25} 26 27// UsingGithubToken will generate a Travis CI API authentication 28// token and call the UsingTravisToken method with it, leaving your 29// client authenticated and ready to use. 30func (as *AuthenticationService) UsingGithubToken(ctx context.Context, githubToken string) (AccessToken, *http.Response, error) { 31 if githubToken == "" { 32 return "", nil, fmt.Errorf("unable to authenticate client; empty github token provided") 33 } 34 35 b := map[string]string{"github_token": githubToken} 36 h := map[string]string{"Accept": mediaTypeV2} 37 38 req, err := as.client.NewRequest(http.MethodPost, "/auth/github", b, h) 39 if err != nil { 40 return "", nil, err 41 } 42 43 // This is the only place you need to access Travis API v2.1 44 // See https://github.com/travis-ci/travis-ci/issues/9273 45 // FIXME Use API V3 once compatible API is implemented 46 req.Header.Del("Travis-API-Version") 47 48 atr := &accessTokenResponse{} 49 resp, err := as.client.Do(ctx, req, atr) 50 if err != nil { 51 return "", nil, err 52 } 53 54 as.UsingTravisToken(string(atr.Token)) 55 56 return atr.Token, resp, err 57} 58 59// UsingTravisToken will format and write provided 60// travisToken in the AuthenticationService client's headers. 61func (as *AuthenticationService) UsingTravisToken(travisToken string) error { 62 if travisToken == "" { 63 return fmt.Errorf("unable to authenticate client; empty travis token provided") 64 } 65 66 as.client.Headers["Authorization"] = "token " + travisToken 67 68 return nil 69} 70