-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathoauthconsumer.go
358 lines (271 loc) · 9.14 KB
/
oauthconsumer.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package oauth
import(
"fmt"
"http"
"rand"
"strconv"
"time"
"sort"
"strings"
"bytes"
"crypto/hmac"
"io/ioutil"
"os"
)
type OAuthConsumer struct{
Service string
RequestTokenURL string
AccessTokenURL string
AuthorizationURL string
ConsumerKey string
ConsumerSecret string
CallBackURL string
requestTokens []*RequestToken
AdditionalParams Params
}
// GetRequestAuthorizationURL Returns the URL for the visitor to Authorize the Access
func (oc *OAuthConsumer) GetRequestAuthorizationURL() (string, *RequestToken, os.Error){
// Gather the params
p := Params{}
// Add required OAuth params
p.Add( &Pair{ Key:"oauth_version", Value:"1.0" } )
p.Add( &Pair{ Key:"oauth_timestamp", Value:strconv.Itoa64(time.Seconds()) } )
p.Add( &Pair{ Key:"oauth_consumer_key", Value:oc.ConsumerKey } )
p.Add( &Pair{ Key:"oauth_callback", Value:oc.CallBackURL } )
p.Add( &Pair{ Key:"oauth_nonce", Value:strconv.Itoa64(rand.Int63()) } )
p.Add( &Pair{ Key:"oauth_signature_method", Value:"HMAC-SHA1" } )
// Sort the collection
sort.Sort(p)
// Generate string of sorted params
sigBaseCol := make([]string, len(p) + len(oc.AdditionalParams))
for i := range p {
sigBaseCol[i] = Encode(p[i].Key) + "=" + Encode( p[i].Value )
}
buf := &bytes.Buffer{}
i := len(p)
for _, kv := range oc.AdditionalParams{
buf.Write([]byte(kv.Key + "=" + Encode( kv.Value ) + ""))
sigBaseCol[i] = kv.Key + "=" + Encode( kv.Value )
i++
}
sigBaseStr := "GET&" +
Encode(oc.RequestTokenURL) + "&" +
Encode(strings.Join(sigBaseCol, "&"))
// Generate Composite Signing key
key := Encode(oc.ConsumerSecret) + "&" + "" // token secrect is blank on the Request Token
// Generate Signature
d := oc.digest(key, sigBaseStr)
// Build Auth Header
authHeader := "OAuth "
for i := range p {
authHeader += p[i].Key + "=\"" + Encode(p[i].Value ) + "\", "
}
// Add the signature
authHeader += "oauth_signature=\"" + Encode(d) + "\""
headers := map[string]string{
"Content-Type":"text/plain",
"Authorization":authHeader,
}
lAddParams := len(oc.AdditionalParams)
if lAddParams > 0 {
oc.RequestTokenURL += "?" + string(buf.Bytes())
}
r, err := get(oc.RequestTokenURL, headers)
if err != nil {
return "", nil, err
}
if r.StatusCode != 200 {
// OAuth service returned an error
return "", nil, os.NewError("OAuth Service returned an error : " + r.Status )
}
b, _ := ioutil.ReadAll( r.Body )
s := string(b)
rt := &RequestToken{}
if strings.Index(s, "&") == -1 {
// Body is empty
return "", nil, os.NewError("Empty response from server")
}
vals := strings.SplitN(s, "&", 10)
for i := range vals {
if strings.Index(vals[i], "=") > -1 {
kv := strings.SplitN(vals[i], "=", 2)
if len(kv) > 0 { // Adds the key even if there's no value.
switch kv[0]{
case "oauth_token": if len(kv) > 1 { rt.Token = kv[1] }; break
case "oauth_token_secret": if len(kv) > 1 { rt.Secret = kv[1] }; break
}
}
}
}
oc.appendRequestToken(rt)
return oc.AuthorizationURL + "?oauth_token=" + rt.Token, rt, nil
}
// GetAccessToken gets the access token for the response from the Authorization URL
func (oc *OAuthConsumer) GetAccessToken(token string, verifier string, ) *AccessToken{
var rt *RequestToken
// Match the RequestToken by Token
for i := range oc.requestTokens {
if oc.requestTokens[i].Token == token ||
oc.requestTokens[i].Token == Encode(token) {
rt = oc.requestTokens[i]
}
}
rt.Verifier = verifier
// Gather the params
p := Params{}
// Add required OAuth params
p.Add( &Pair{ Key:"oauth_consumer_key", Value:oc.ConsumerKey } )
p.Add( &Pair{ Key:"oauth_token", Value:rt.Token })
p.Add( &Pair{ Key:"oauth_verifier", Value:rt.Verifier })
p.Add( &Pair{ Key:"oauth_signature_method", Value:"HMAC-SHA1" } )
p.Add( &Pair{ Key:"oauth_timestamp", Value:strconv.Itoa64(time.Seconds()) } )
p.Add( &Pair{ Key:"oauth_nonce", Value:strconv.Itoa64(rand.Int63()) } )
p.Add( &Pair{ Key:"oauth_version", Value:"1.0" } )
// Sort the collection
sort.Sort(p)
// Generate string of sorted params
sigBaseCol := make([]string, len(p))
for i := range p {
sigBaseCol[i] = Encode(p[i].Key) + "=" + Encode( p[i].Value )
}
sigBaseStr := "POST&" +
Encode(oc.AccessTokenURL) + "&" +
Encode(strings.Join(sigBaseCol, "&"))
sigBaseStr= strings.Replace(sigBaseStr, Encode(Encode(rt.Token)), Encode(rt.Token), 1)
// Generate Composite Signing key
key := Encode(oc.ConsumerSecret) + "&" + rt.Secret
// Generate Signature
d := oc.digest(key, sigBaseStr)
// Build Auth Header
authHeader := "OAuth "
for i := range p {
authHeader += p[i].Key + "=\"" + Encode(p[i].Value ) + "\", "
}
// Add the signature
authHeader += "oauth_signature=\"" + Encode(d) + "\""
authHeader = strings.Replace(authHeader, Encode(rt.Token), rt.Token, 1)
// Add Header & Buffer for params
buf := &bytes.Buffer{}
headers := map[string]string{
"Content-Type":"application/x-www-form-urlencoded",
"Authorization":authHeader,
}
// Action the POST to get the AccessToken
r, err := post(oc.AccessTokenURL, headers, buf)
if err != nil {
fmt.Println(err.String())
return nil
}
// Read response Body & Create AccessToken
b, _ := ioutil.ReadAll( r.Body )
s := string(b)
at := &AccessToken{ Service:oc.Service }
if strings.Index(s, "&") > -1 {
vals := strings.SplitN(s, "&", 10)
for i := range vals {
if strings.Index(vals[i], "=") > -1 {
kv := strings.SplitN(vals[i], "=", 2)
if len(kv) > 0 { // Adds the key even if there's no value.
switch kv[0]{
case "oauth_token": if len(kv) > 1 { at.Token = kv[1] }; break
case "oauth_token_secret": if len(kv) > 1 { at.Secret = kv[1] }; break
}
}
}
}
}
// Return the AccessToken
return at
}
// OAuthRequestGet return the response via a GET for the url with the AccessToken passed
func (oc *OAuthConsumer) Get( url string, fparams Params, at *AccessToken) (r *http.Response, err os.Error) {
return oc.oAuthRequest(url, fparams, at, "GET")
}
// OAuthRequest returns the response via a POST for the url with the AccessToken passed & the Form params passsed in fparams
func (oc *OAuthConsumer) Post( url string, fparams Params, at *AccessToken) (r *http.Response, err os.Error) {
return oc.oAuthRequest( url, fparams, at, "POST")
}
func (oc *OAuthConsumer) oAuthRequest( url string, fparams Params, at *AccessToken, method string) (r *http.Response, err os.Error) {
// Gather the params
p := Params{}
hp := Params{}
// Add required OAuth params
p.Add( &Pair{ Key:"oauth_token", Value:at.Token })
p.Add( &Pair{ Key:"oauth_signature_method", Value:"HMAC-SHA1" } )
p.Add( &Pair{ Key:"oauth_consumer_key", Value:oc.ConsumerKey } )
p.Add( &Pair{ Key:"oauth_timestamp", Value:strconv.Itoa64(time.Seconds()) } )
p.Add( &Pair{ Key:"oauth_nonce", Value:strconv.Itoa64(rand.Int63()) } )
p.Add( &Pair{ Key:"oauth_version", Value:"1.0" } )
// Add the params to the Header collection
for i := range p {
hp.Add( &Pair{ Key:p[i].Key, Value:p[i].Value } )
}
fparamsStr := ""
// Add any additional params passed
for i := range fparams{
k, v := fparams[i].Key, fparams[i].Value
p.Add( &Pair{ Key:k, Value:v } )
fparamsStr += k + "=" + Encode(v) + "&"
}
// Sort the collection
sort.Sort(p)
// Generate string of sorted params
sigBaseCol := make([]string, len(p))
for i := range p {
sigBaseCol[i] = Encode(p[i].Key) + "=" + Encode( p[i].Value )
}
sigBaseStr := method + "&" +
Encode(url) + "&" +
Encode(strings.Join(sigBaseCol, "&"))
sigBaseStr= strings.Replace(sigBaseStr, Encode(Encode(at.Token)), Encode(at.Token), 1)
// Generate Composite Signing key
key := Encode( oc.ConsumerSecret ) + "&" + at.Secret
// Generate Signature
d := oc.digest(key, sigBaseStr)
// Build Auth Header
authHeader := "OAuth "
for i := range hp {
if strings.Index(hp[i].Key, "oauth") == 0 {
//Add it to the authHeader
authHeader += hp[i].Key + "=\"" + Encode(hp[i].Value ) + "\", "
}
}
// Add the signature
authHeader += "oauth_signature=\"" + Encode(d) + "\""
authHeader = strings.Replace(authHeader, Encode(at.Token), at.Token, 1)
// Add Header & Buffer for params
buf := bytes.NewBufferString(fparamsStr)
headers := map[string]string{
"Authorization":authHeader,
}
if method == "GET" {
// return Get response
return get(url + "?" + fparamsStr, headers)
}
// return POSTs response
return post(url, headers, buf)
}
// digest Generates a HMAC-1234 for the signature
func (oc *OAuthConsumer) digest(key string, m string) string {
h := hmac.NewSHA1([]byte(key))
h.Write([]byte(m))
return base64encode(h.Sum())
/* s := bytes.TrimSpace(h.Sum())
d := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
base64.StdEncoding.Encode(d, s)
ds := strings.TrimSpace(bytes.NewBuffer(d).String())
*/
// return ds
}
// appendRequestToken adds the Request Tokens to a localy temp collection
func (oc *OAuthConsumer) appendRequestToken(token *RequestToken){
if oc.requestTokens == nil { oc.requestTokens = make([]*RequestToken, 0, 4) }
n := len(oc.requestTokens)
if n+1 > cap(oc.requestTokens) {
s := make([]*RequestToken, n, 2*n+1)
copy(s, oc.requestTokens)
oc.requestTokens = s
}
oc.requestTokens = oc.requestTokens[0 : n+1]
oc.requestTokens[n] = token
}