-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathauthentication.go
67 lines (54 loc) · 1.58 KB
/
authentication.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
package codeship
import (
"context"
"encoding/json"
"net/http"
"unicode"
"github.com/pkg/errors"
)
// ErrUnauthorized occurs when Codeship returns a 401 Unauthorized response
type ErrUnauthorized string
func (e ErrUnauthorized) Error() string {
return string(e)
}
// Authentication object holds access token and scope information
type Authentication struct {
AccessToken string `json:"access_token,omitempty"`
Organizations []struct {
Name string `json:"name,omitempty"`
UUID string `json:"uuid,omitempty"`
Scopes []string `json:"scopes,omitempty"`
} `json:"organizations,omitempty"`
ExpiresAt int64 `json:"expires_at,omitempty"`
}
// Authenticate swaps username/password for an authentication token
//
// Codeship API docs: https://apidocs.codeship.com/v2/authentication/authentication-endpoint
func (c *Client) Authenticate(ctx context.Context) (Response, error) {
path := "/auth"
req, _ := http.NewRequest("POST", c.baseURL+path, nil)
c.authenticator.SetAuth(req)
req.Header.Set("Content-Type", "application/json")
c.authentication = Authentication{}
body, resp, err := c.do(req.WithContext(ctx))
if err != nil {
return resp, err
}
var auth = &struct {
Authentication
Error string `json:"error,omitempty"`
}{}
if err = json.Unmarshal(body, auth); err != nil {
return resp, errors.Wrap(err, "unable to unmarshal JSON")
}
if auth.Error != "" {
return resp, toError(auth.Error)
}
c.authentication = auth.Authentication
return resp, err
}
func toError(msg string) error {
s := []rune(msg)
s[0] = unicode.ToLower(s[0])
return errors.New(string(s))
}