/
userconfig.go
246 lines (192 loc) · 6.9 KB
/
userconfig.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
236
237
238
239
240
241
242
243
244
245
246
// Copyright 2011 Arne Roomann-Kurrik.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oauth1a
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// UserConfig is a container for user-specific keys and secrets related to the OAuth process.
// This struct is intended to be serialized and stored for future use.
// Request and Access tokens are each stored separately, so that the current
// position in the auth flow may be inferred.
type UserConfig struct {
RequestTokenSecret string
RequestTokenKey string
AccessTokenSecret string
AccessTokenKey string
Verifier string
AccessValues url.Values
}
// NewAuthorizedConfig creates a UserConfig object with existing access token credentials.
// For users where an access token has been obtained through other means than
// the authz flows provided by this library.
func NewAuthorizedConfig(token string, secret string) *UserConfig {
return &UserConfig{AccessTokenKey: token, AccessTokenSecret: secret}
}
// Sign and send a Request using the current configuration.
func (c *UserConfig) send(request *http.Request, service *Service, client *http.Client) (*http.Response, error) {
if err := service.Sign(request, c); err != nil {
return nil, err
}
response, err := client.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(io.LimitReader(response.Body, errBodyLimit))
return nil, fmt.Errorf("Endpoint response: %v %v", response.Status, string(body))
}
return response, nil
}
// GetRequestToken issues a request to obtain a Request token.
func (c *UserConfig) GetRequestToken(ctx context.Context, service *Service, client *http.Client) error {
data := url.Values{}
if service.ClientConfig.CallbackURL != "" {
data.Set("oauth_callback", service.ClientConfig.CallbackURL)
}
body := strings.NewReader(data.Encode())
request, err := http.NewRequestWithContext(ctx, http.MethodPost, service.RequestURL, body)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := c.send(request, service, client)
if err != nil {
return err
}
err = c.parseRequestToken(response)
return err
}
// Given the returned response from a Request token request, parse out the
// appropriate request token and secret fields.
func (c *UserConfig) parseRequestToken(response *http.Response) error {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
params, err := url.ParseQuery(string(body))
if err != nil {
return err
}
tokenKey := params.Get("oauth_token")
tokenSecret := params.Get("oauth_token_secret")
if tokenKey == "" || tokenSecret == "" {
return fmt.Errorf("No token or secret found")
}
c.RequestTokenKey = tokenKey
c.RequestTokenSecret = tokenSecret
if params.Get("oauth_callback_confirmed") == "false" {
return fmt.Errorf("OAuth callback not confirmed")
}
return nil
}
// GetAuthorizeURL obtains a URL which will allow the current user to authorize access to their
// OAuth-protected data.
func (c *UserConfig) GetAuthorizeURL(service *Service) (string, error) {
if c.RequestTokenKey == "" || c.RequestTokenSecret == "" {
return "", fmt.Errorf("No configured request token")
}
token := url.QueryEscape(c.RequestTokenKey)
return service.AuthorizeURL + "?oauth_token=" + token, nil
}
// ParseAuthorize parses an access token and verifier from a redirected authorize request.
func (c *UserConfig) ParseAuthorize(request *http.Request, service *Service) (string, string, error) {
if err := request.ParseForm(); err != nil {
return "", "", err
}
urlParts := request.URL.Query()
token := urlParts.Get("oauth_token")
verifier := urlParts.Get("oauth_verifier")
if token == "" {
token = request.Form.Get("oauth_token")
}
if verifier == "" {
verifier = request.Form.Get("oauth_verifier")
}
if token == "" || verifier == "" {
return "", "", fmt.Errorf("Token or verifier were missing from response")
}
return token, verifier, nil
}
// GetAccessToken issues a request to exchange the current request token for an access token.
func (c *UserConfig) GetAccessToken(ctx context.Context, token string, verifier string, service *Service, client *http.Client) error {
// This code used to error out if RequestTokenKey were empty, but
// in the interest of being able to operate in a stateless manner this
// has been removed. If you want to make sure that the request token
// is validated against what is being returned, populate the UserConfig
// with a request token stored server-side somewhere, accessed by the
// user's session.
if c.RequestTokenKey != "" && c.RequestTokenKey != token {
return fmt.Errorf("Returned token did not match request token")
}
c.Verifier = verifier
data := url.Values{}
if service.ClientConfig.CallbackURL != "" {
data.Set("oauth_verifier", verifier)
}
body := strings.NewReader(data.Encode())
request, err := http.NewRequestWithContext(ctx, http.MethodPost, service.AccessURL, body)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := c.send(request, service, client)
if err != nil {
return err
}
err = c.parseAccessToken(response)
return err
}
// Given the returned response from the access token request, pull out the
// access token and token secret. Store a copy of any other values returned,
// too, since some services (like Twitter) return handy information such
// as the username.
func (c *UserConfig) parseAccessToken(response *http.Response) error {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
params, err := url.ParseQuery(string(body))
if err != nil {
return err
}
tokenKey := params.Get("oauth_token")
tokenSecret := params.Get("oauth_token_secret")
if tokenKey == "" || tokenSecret == "" {
return fmt.Errorf("No token or secret found")
}
c.AccessTokenKey = tokenKey
c.AccessTokenSecret = tokenSecret
c.AccessValues = params
return nil
}
// GetToken returns a token and secret corresponding to where in the OAuth flow this
// config is currently in. The priority is Access token, Request token, empty
// string.
func (c *UserConfig) GetToken() (string, string) {
if c.AccessTokenKey != "" {
return c.AccessTokenKey, c.AccessTokenSecret
}
if c.RequestTokenKey != "" {
return c.RequestTokenKey, c.RequestTokenSecret
}
return "", ""
}