GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#29)
by
unknown
01:21
created

mollie.*Client.WithAuthenticationValue   A

Complexity

Conditions 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
nop 1
1
package mollie
2
3
import (
4
	"bytes"
5
	"encoding/json"
6
	"errors"
7
	"fmt"
8
	"io"
9
	"io/ioutil"
10
	"net/http"
11
	"net/url"
12
	"os"
13
	"strings"
14
)
15
16
// Mollie  constants holding values to initialize the client and create requests.
17
const (
18
	BaseURL            string = "https://api.mollie.com/"
19
	AuthHeader         string = "Authorization"
20
	TokenType          string = "Bearer"
21
	APITokenEnv        string = "MOLLIE_API_TOKEN"
22
	OrgTokenEnv        string = "MOLLIE_ORG_TOKEN"
23
	RequestContentType string = "application/json"
24
)
25
26
var (
27
	errEmptyAPIKey = errors.New("you must provide a non-empty API key")
28
	errBadBaseURL  = errors.New("malformed base url, it must contain a trailing slash")
29
)
30
31
// Client manages communication with Mollie's API.
32
type Client struct {
33
	BaseURL        *url.URL
34
	authentication string
35
	client         *http.Client
36
	common         service // Reuse a single struct instead of allocating one for each service on the heap.
37
	config         *Config
38
	// Services
39
	Payments    *PaymentsService
40
	Chargebacks *ChargebacksService
41
	Methods     *MethodsService
42
	Invoices    *InvoicesService
43
}
44
45
type service struct {
46
	client *Client
47
}
48
49
// WithAuthenticationValue offers a convenient setter for any of the valid authentication
50
// tokens provided by Mollie.
51
//
52
// Ideally your API key will be provided from and environment variable or
53
// a secret management engine.
54
// This should only be used when environment variables are "impossible" to be used.
55
func (c *Client) WithAuthenticationValue(k string) error {
56 1
	if k == "" {
57 1
		return errEmptyAPIKey
58
	}
59
60 1
	c.authentication = strings.TrimSpace(k)
61
62 1
	return nil
63
}
64
65
// NewAPIRequest is a wrapper around the http.NewRequest function.
66
//
67
// It will setup the authentication headers/parameters according to the client config.
68
func (c *Client) NewAPIRequest(method string, uri string, body interface{}) (req *http.Request, err error) {
69 1
	if !strings.HasSuffix(c.BaseURL.Path, "/") {
70 1
		return nil, errBadBaseURL
71
	}
72
73 1
	u, err := c.BaseURL.Parse(uri)
74 1
	if err != nil {
75 1
		return nil, err
76
	}
77
78 1
	if c.config.testing == true {
79 1
		u.Query().Add("testmode", "true")
80
	}
81
82 1
	var buf io.ReadWriter
83 1
	if body != nil {
84 1
		buf = new(bytes.Buffer)
85 1
		enc := json.NewEncoder(buf)
86 1
		enc.SetEscapeHTML(false)
87 1
		err := enc.Encode(body)
88 1
		if err != nil {
89 1
			return nil, err
90
		}
91
	}
92
93 1
	req, err = http.NewRequest(method, u.String(), buf)
94 1
	if err != nil {
95 1
		return nil, err
96
	}
97
98 1
	req.Header.Add(AuthHeader, strings.Join([]string{TokenType, c.authentication}, " "))
99
100 1
	if body != nil {
101 1
		req.Header.Set("Content-Type", RequestContentType)
102
	}
103 1
	req.Header.Set("Accept", RequestContentType)
104
105 1
	return
106
}
107
108
// Do sends an API request and returns the API response or returned as an
109
// error if an API error has occurred.
110
func (c *Client) Do(req *http.Request) (*Response, error) {
111 1
	resp, err := c.client.Do(req)
112 1
	if err != nil {
113
		return nil, err
114
	}
115 1
	defer resp.Body.Close()
116 1
	response := newResponse(resp)
117 1
	err = CheckResponse(resp)
118 1
	if err != nil {
119 1
		return nil, err
120
	}
121
122 1
	return response, nil
123
}
124
125
// NewClient returns a new Mollie HTTP API client.
126
// You can pass a previously build http client, if none is provided then
127
// http.DefaultClient will be used.
128
//
129
// NewClient will lookup the environment for values to assign to the
130
// API token (`MOLLIE_API_TOKEN`) and the Organization token (`MOLLIE_ORG_TOKEN`)
131
// according to the provided Config object.
132
//
133
// You can also set the token values programmatically by using the Client
134
// WithAPIKey and WithOrganizationKey functions.
135
func NewClient(baseClient *http.Client, c *Config) (mollie *Client, err error) {
136 1
	if baseClient == nil {
137 1
		baseClient = http.DefaultClient
138
	}
139
140 1
	u, _ := url.Parse(BaseURL)
141
142 1
	mollie = &Client{
143
		BaseURL: u,
144
		client:  baseClient,
145
		config:  c,
146
	}
147
148 1
	mollie.common.client = mollie
149
150
	// services for resources
151 1
	mollie.Payments = (*PaymentsService)(&mollie.common)
152 1
	mollie.Chargebacks = (*ChargebacksService)(&mollie.common)
153 1
	mollie.Methods = (*MethodsService)(&mollie.common)
154 1
	mollie.Invoices = (*InvoicesService)(&mollie.common)
155
156
	// Parse authorization from environment
157 1
	if tkn, ok := os.LookupEnv(APITokenEnv); ok {
158 1
		mollie.authentication = tkn
159
	}
160 1
	return
161
}
162
163
/*
164
Error reports details on a failed API request.
165
The success or failure of each HTTP request is shown in the status field of the HTTP response header,
166
which contains standard HTTP status codes:
167
- a 2xx code for success
168
- a 4xx or 5xx code for failure
169
*/
170
type Error struct {
171
	Code     int            `json:"code"`
172
	Message  string         `json:"message"`
173
	Response *http.Response `json:"response"` // the full response that produced the error
174
}
175
176
// Error functions implement the Error interface on the zuora.Error struct.
177
func (e *Error) Error() string {
178 1
	return fmt.Sprintf("response failed with status %v", e.Message)
179
}
180
181
/*
182
Constructor for Error
183
*/
184
func newError(r *http.Response) *Error {
185 1
	var e Error
186 1
	e.Response = r
187 1
	e.Code = r.StatusCode
188 1
	e.Message = r.Status
189 1
	return &e
190
}
191
192
// Response is a Mollie API response. This wraps the standard http.Response
193
// returned from Mollie and provides convenient access to things like
194
// pagination links.
195
type Response struct {
196
	*http.Response
197
	content []byte
198
}
199
200
func newResponse(r *http.Response) *Response {
201 1
	var res Response
202 1
	if c, err := ioutil.ReadAll(r.Body); err == nil {
203 1
		res.content = c
204
	}
205 1
	json.NewDecoder(r.Body).Decode(&res)
206 1
	res.Response = r
207 1
	return &res
208
}
209
210
// CheckResponse checks the API response for errors, and returns them if
211
// present. A response is considered an error if it has a status code outside
212
// the 200 range.
213
// API error responses are expected to have either no response
214
// body, or a JSON response body.
215
func CheckResponse(r *http.Response) error {
216 1
	if r.StatusCode >= http.StatusMultipleChoices {
217 1
		return newError(r)
218
	}
219 1
	return nil
220
}
221