-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth.go
235 lines (200 loc) · 6.5 KB
/
oauth.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package oauth
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"strings"
)
type HttpClientFactory func() *http.Client
// TokenResponse represents successful token response
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
}
// ErrorResponse repsents a failed response
type ErrorResponse struct {
Error string `json:"error"`
Description string `json:"error_description"`
}
// OauthClient represents a stateful Oauth client
type OauthClient struct {
Service string
Client *http.Client
Headers map[string]string
ClientID string
ClientSecret string
SourceHeader string
ResponseHeaders http.Header
AppID string
Scope string
Token string
SkipCertVerify bool
}
// OauthConfig represents configuration used to create Oauth clients
type OauthConfig struct {
ClientID string `json:"clientID" structs:"clientID" mapstructure:"clientID"`
ClientSecret string `json:"clientSecret" structs:"clientSecret" mapstructure:"clientSecret"`
ServiceURL string `json:"serviceUrl" structs:"serviceUrl" mapstructure:"serviceUrl"`
AppID string `json:"appID" structs:"appID" mapstructure:"appID"`
Scope string `json:"scope,omitempty" structs:"scope" mapstructure:"scope"`
Policies []string `json:"policies,omitempty" structs:"policies" mapstructure:"policies"`
SkipCertVerify bool `json:"skipCertVerify,omitempty" structs:"skipCertVerify" mapstructure:"skipCertVerify"`
}
// GetConfig reads config from a file specified as arg or from the environment
func GetConfig(configPath string) (*OauthConfig, error) {
var config OauthConfig
// No path specified; use environment
if configPath == "" {
path, found := os.LookupEnv("CENTRIFY_OAUTH_CONFIGPATH")
if found {
configPath = path
}
}
if configPath != "" {
fileBytes, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("error reading configuration from path '%s': %s", configPath, err)
}
err = json.Unmarshal(fileBytes, &config)
if err != nil {
return nil, fmt.Errorf("error demarshalling configuration from path '%s': %s", configPath, err)
}
}
return &config, nil
}
// GetNewClient creates a new client for the specified endpoint
func GetNewClient(service string, httpFactory HttpClientFactory) (*OauthClient, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
// Munge on the service a little bit, force it to have no trailing / and always start with https://
url, err := url.Parse(service)
if err != nil {
return nil, err
}
url.Scheme = "https"
url.Path = ""
client := &OauthClient{}
client.Service = url.String()
if httpFactory != nil {
client.Client = httpFactory()
} else {
client.Client = &http.Client{}
}
client.Client.Jar = jar
client.Headers = make(map[string]string)
client.SourceHeader = "cloud-golang-sdk"
return client, err
}
// GetNewConfidentialClient creates a new client for the specified endpoint
func GetNewConfidentialClient(service string, clientID string, clientSecret string, httpFactory HttpClientFactory) (*OauthClient, error) {
client, err := GetNewClient(service, httpFactory)
if err != nil {
return nil, err
}
client.ClientID = clientID
client.ClientSecret = clientSecret
return client, nil
}
// ResourceOwner implements the ResourceOwner flow
func (c *OauthClient) ResourceOwner(appID string, scope string, owner string, ownerPassword string) (*TokenResponse, *ErrorResponse, error) {
args := make(map[string]string)
args["grant_type"] = "password"
args["username"] = owner
args["password"] = ownerPassword
args["scope"] = scope
return c.postAndGetResponse("/oauth2/token/"+appID, args)
}
func (c *OauthClient) ClientCredentials(appID string, scope string) (*TokenResponse, *ErrorResponse, error) {
args := make(map[string]string)
args["grant_type"] = "client_credentials"
args["scope"] = scope
return c.postAndGetResponse("/oauth2/token/"+appID, args)
}
func (c *OauthClient) RefreshToken(appID string, refreshToken string) (*TokenResponse, *ErrorResponse, error) {
args := make(map[string]string)
args["grant_type"] = "refresh_token"
args["refresh_token"] = refreshToken
return c.postAndGetResponse("/oauth2/token/"+appID, args)
}
func (c *OauthClient) postAndGetResponse(method string, args map[string]string) (*TokenResponse, *ErrorResponse, error) {
body, status, err := c.postAndGetBody(method, args)
if err != nil {
return nil, nil, err
}
if status == 200 {
response, err := bodyToTokenResponse(body)
if err != nil {
return nil, nil, err
}
return response, nil, nil
}
response, err := bodyToErrorResponse(body)
if err != nil {
return nil, nil, err
}
return nil, response, nil
}
func (c *OauthClient) postAndGetBody(method string, args map[string]string) ([]byte, int, error) {
postdata := strings.NewReader(payloadFromMap(args))
postreq, err := http.NewRequest("POST", c.Service+method, postdata)
if err != nil {
return nil, 0, err
}
if c.ClientID != "" && c.ClientSecret != "" {
postreq.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(c.ClientID+":"+c.ClientSecret)))
}
postreq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
postreq.Header.Add("X-CENTRIFY-NATIVE-CLIENT", "Yes")
postreq.Header.Add("X-CFY-SRC", c.SourceHeader)
for k, v := range c.Headers {
postreq.Header.Add(k, v)
}
httpresp, err := c.Client.Do(postreq)
if err != nil {
c.ResponseHeaders = nil
return nil, 0, err
}
defer httpresp.Body.Close()
c.ResponseHeaders = httpresp.Header
body, err := ioutil.ReadAll(httpresp.Body)
if err != nil {
return nil, httpresp.StatusCode, err
}
return body, httpresp.StatusCode, nil
}
// GetLastResponseHeaders returns the response header for the previous REST call
func (c *OauthClient) GetLastResponseHeaders() http.Header {
return c.ResponseHeaders
}
func payloadFromMap(input map[string]string) string {
data := url.Values{}
for i, v := range input {
data.Add(i, v)
}
return data.Encode()
}
func bodyToTokenResponse(body []byte) (*TokenResponse, error) {
reply := &TokenResponse{}
err := json.Unmarshal(body, &reply)
if err != nil {
return nil, err
}
return reply, nil
}
func bodyToErrorResponse(body []byte) (*ErrorResponse, error) {
reply := &ErrorResponse{}
err := json.Unmarshal(body, &reply)
if err != nil {
return nil, err
}
return reply, nil
}