/
authentication.go
117 lines (87 loc) · 2.24 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package bankly
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
"time"
)
//Authentication ...
type Authentication struct {
session Session
httpClient *http.Client
}
//NewAuthentication ...
func NewAuthentication(httpClient *http.Client, session Session) *Authentication {
return &Authentication{
session: session,
httpClient: httpClient,
}
}
func (a *Authentication) login(ctx context.Context) (*AuthenticationResponse, error) {
u, err := url.Parse(a.session.LoginEndpoint)
if err != nil {
return nil, err
}
if a.session.Mtls {
u.Path = path.Join(u.Path, LoginMtlsPath)
} else {
u.Path = path.Join(u.Path, LoginPath)
}
endpoint := u.String()
formData := url.Values{
"grant_type": {"client_credentials"},
"client_id": {a.session.ClientID},
}
if !a.session.Mtls {
formData.Add("client_secret", a.session.ClientSecret)
}
if len(a.session.Scopes) > 0 {
formData.Add("scope", a.session.Scopes)
}
req, err := http.NewRequestWithContext(ctx, "POST", endpoint, strings.NewReader(formData.Encode()))
if err != nil {
return nil, err
}
req.Header.Add("Content-type", "application/x-www-form-urlencoded")
resp, err := a.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var response *AuthenticationResponse
respBody, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(respBody, &response)
if err != nil {
return nil, err
}
return response, nil
}
if resp.StatusCode == http.StatusBadRequest {
var bodyErr *ErrorLoginResponse
respBody, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(respBody, &bodyErr)
if err != nil {
return nil, err
}
return nil, FindError("400", bodyErr.Message)
}
return nil, ErrDefaultLogin
}
//Token ...
func (a Authentication) Token(ctx context.Context) (string, error) {
if token, found := a.session.Cache.Get("token"); found {
return token.(string), nil
}
response, err := a.login(ctx)
if err != nil {
return "", err
}
a.session.Cache.Set("token", fmt.Sprintf("%s %s", "Bearer", response.AccessToken), time.Second*time.Duration(int64(response.ExpiresIn-10)))
return fmt.Sprintf("%s %s", "Bearer", response.AccessToken), nil
}