/
auth.go
83 lines (71 loc) · 2.38 KB
/
auth.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2014 Mark Wolfe. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package buildkite
import (
"encoding/base64"
"fmt"
"net/http"
)
// TokenAuthTransport manages injection of the API token for each request
type TokenAuthTransport struct {
APIToken string
APIHost string
Transport http.RoundTripper
}
// RoundTrip invoked each time a request is made
func (t TokenAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.URL.Host == t.APIHost || t.APIHost == "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", t.APIToken))
}
return t.transport().RoundTrip(req)
}
// Client builds a new http client.
func (t *TokenAuthTransport) Client() *http.Client {
return &http.Client{Transport: t}
}
func (t *TokenAuthTransport) transport() http.RoundTripper {
// Use the custom transport if one was provided
if t.Transport != nil {
return t.Transport
}
return http.DefaultTransport
}
// NewTokenConfig configure authentication using an API token
// NOTE: the debug flag is not used anymore.
func NewTokenConfig(apiToken string, debug bool) (*TokenAuthTransport, error) {
if apiToken == "" {
return nil, fmt.Errorf("Invalid token, empty string supplied")
}
return &TokenAuthTransport{APIToken: apiToken}, nil
}
// BasicAuthTransport manages injection of the authorization header
type BasicAuthTransport struct {
APIHost string
Username string
Password string
}
// RoundTrip invoked each time a request is made
func (bat BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.URL.Host == bat.APIHost || bat.APIHost == "" {
req.Header.Set("Authorization", fmt.Sprintf("Basic %s",
base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s",
bat.Username, bat.Password)))))
}
return http.DefaultTransport.RoundTrip(req)
}
// Client builds a new http client.
func (bat *BasicAuthTransport) Client() *http.Client {
return &http.Client{Transport: bat}
}
// NewBasicConfig configure authentication using the supplied credentials
func NewBasicConfig(username string, password string) (*BasicAuthTransport, error) {
if username == "" {
return nil, fmt.Errorf("Invalid username, empty string supplied")
}
if password == "" {
return nil, fmt.Errorf("Invalid password, empty string supplied")
}
return &BasicAuthTransport{"", username, password}, nil
}