-
Notifications
You must be signed in to change notification settings - Fork 9
/
oauth.go
305 lines (262 loc) · 7.03 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
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
// A Go OAuth library, mainly created to interact with Twitter.
//
// Does header-based OAuth over HTTP or HTTPS.
package oauth
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"math/rand"
"net/http"
"sort"
"strconv"
"time"
)
// Supported oauth version (currently the only legal value):
const OAUTH_VERSION = "1.0"
// Supported signature methods:
const (
HMAC_SHA1 = "HMAC-SHA1"
)
// Request types:
const (
TempCredentialReq = iota
OwnerAuthorization
TokenReq
)
type OAuth struct {
ConsumerKey string
ConsumerSecret string
SignatureMethod string
Callback string
RequestTokenURL string
OwnerAuthURL string
AccessTokenURL string
AccessToken string
AccessSecret string
// NOT initialized.
RequestTokenParams map[string]string
RequestToken string
RequestSecret string
userName string
userId uint
}
// An empty map[string]string.
// Caters to laziness when no params are given.
var None map[string]string
func (o *OAuth) Authorized() bool {
if o.AccessToken != "" && o.AccessSecret != "" {
return true
}
return false
}
// Returns the user id, if any.
//
// Does not return any dance errors, because that would just be
// obnoxious. Check for authorization with Authorized().
func (o *OAuth) UserID() uint {
return o.userId
}
// Returns the username, if any.
//
// Does not return any dance errors. Check for authorization with
// Authorized().
func (o *OAuth) UserName() string {
return o.userName
}
// Initiates the OAuth dance.
func (o *OAuth) GetRequestToken() (err error) {
oParams := o.params()
oParams["oauth_callback"] = o.Callback
allParams := mergeParams(oParams, o.RequestTokenParams)
resp, err := o.makeRequest("POST", o.RequestTokenURL, allParams, None)
if err != nil {
return
}
err = o.parseResponse(resp.StatusCode, resp.Body, TempCredentialReq)
return
}
// Makes an HTTP request, handling all the repetitive OAuth overhead.
func (o *OAuth) makeRequest(method, url string, oParams map[string]string, params map[string]string) (resp *http.Response, err error) {
escapeParams(oParams)
escapeParams(params)
allParams := mergeParams(oParams, params)
signature, err := o.sign(baseString(method, url, allParams))
if err != nil {
return
}
oParams["oauth_signature"] = PercentEncode(signature)
switch method {
case "POST":
resp, err = post(addQueryParams(url, params), oParams)
case "GET":
resp, err = get(addQueryParams(url, params), oParams)
default:
return nil, &implementationError{
What: fmt.Sprintf("HTTP method (%s)", method),
Where: "OAuth\xb7makeRequest()",
}
}
return
}
// The URL the user needs to visit to grant authorization.
// Call after GetRequestToken().
func (o *OAuth) AuthorizationURL() (string, error) {
if o.RequestToken == "" || o.RequestSecret == "" {
return "", &danceError{
What: "attempt to get authorization without credentials",
Where: "OAuth\xb7AuthorizationURL()",
}
}
url := o.OwnerAuthURL + "?oauth_token=" + o.RequestToken
return url, nil
}
// Performs the final step in the dance: getting the access token.
//
// Call this after GetRequestToken() and getting user verification.
func (o *OAuth) GetAccessToken(verifier string) (err error) {
if o.RequestToken == "" || o.RequestSecret == "" {
return &danceError{
What: "Temporary credentials not avaiable",
Where: "OAuth\xb7GetAccessToken()",
}
}
params := o.params()
params["oauth_token"] = o.RequestToken
params["oauth_verifier"] = verifier
resp, err := o.makeRequest("POST", o.AccessTokenURL, params, None)
if err != nil {
return
}
return o.parseResponse(resp.StatusCode, resp.Body, TokenReq)
}
// Parses a response for the OAuth dance and sets the appropriate fields
// in o for the request type.
func (o *OAuth) parseResponse(status int, body io.Reader, requestType int) error {
//dump, _ := http.DumpResponse(resp, true)
//fmt.Fprintf(os.Stderr, "%s\n", dump)
r := bodyString(body)
if status == 401 {
return &danceError{
What: r,
Where: fmt.Sprintf("parseResponse(requestType=%d)", requestType),
}
}
params := parseParams(r)
switch requestType {
case TempCredentialReq:
o.RequestToken = params["oauth_token"]
o.RequestSecret = params["oauth_token_secret"]
if confirmed, ok := params["oauth_callback_confirmed"]; !ok ||
confirmed != "true" {
return &callbackError{o.Callback}
}
case TokenReq:
o.AccessToken = params["oauth_token"]
o.AccessSecret = params["oauth_token_secret"]
n, _ := strconv.ParseUint(params["user_id"], 10, 0)
o.userId = uint(n)
o.userName = params["screen_name"]
default:
return &implementationError{
What: "requestType=" + strconv.Itoa(requestType),
Where: "OAuth\xb7parseResponse()",
}
}
return nil
}
func (o *OAuth) params() (p map[string]string) {
p = make(map[string]string)
p["oauth_consumer_key"] = o.ConsumerKey
p["oauth_signature_method"] = o.SignatureMethod
p["oauth_timestamp"] = timestamp()
p["oauth_nonce"] = nonce()
p["oauth_version"] = OAUTH_VERSION
if o.Authorized() {
p["oauth_token"] = o.AccessToken
}
return
}
// The base string used to compute signatures.
//
// Pass in all parameters, (query params, oauth params, post body).
func baseString(method, url string, params map[string]string) string {
str := method + "&"
str += PercentEncode(url)
keys := make([]string, len(params))
i := 0
for k, _ := range params {
keys[i] = k
i++
}
sort.Strings(keys)
first := true
for _, k := range keys {
if first {
str += "&"
first = false
} else {
str += "%26"
}
str += PercentEncode(k) + "%3D"
str += PercentEncode(params[k])
}
return str
}
// For oauth_nonce (if that wasn't obvious).
func nonce() string {
return strconv.FormatInt(rand.Int63(), 10)
}
// This could probably seem like less of a hack...
func (o *OAuth) signingKey() string {
key := o.ConsumerSecret + "&"
if o.AccessSecret != "" {
key += o.AccessSecret
} else if o.RequestSecret != "" {
key += o.RequestSecret
}
return key
}
func (o *OAuth) sign(request string) (string, error) {
key := o.signingKey()
switch o.SignatureMethod {
case HMAC_SHA1:
hash := hmac.New(sha1.New, []byte(key))
hash.Write([]byte(request))
signature := hash.Sum(nil)
digest := make([]byte, base64.StdEncoding.EncodedLen(len(signature)))
base64.StdEncoding.Encode(digest, signature)
return string(digest), nil
}
return "", &implementationError{
What: fmt.Sprintf("Unknown signature method (%d)", o.SignatureMethod),
Where: "OAuth\xb7sign",
}
}
func timestamp() string {
return strconv.FormatInt(time.Now().Unix(), 10)
}
func (o *OAuth) Post(url string, params map[string]string) (r *http.Response, err error) {
if !o.Authorized() {
return nil, &danceError{
What: "Not authorized",
Where: "OAuth\xb7PostParams()",
}
}
oParams := o.params()
r, err = o.makeRequest("POST", url, oParams, params)
return
}
func (o *OAuth) Get(url string, params map[string]string) (r *http.Response, err error) {
if !o.Authorized() {
return nil, &danceError{
What: "Not authorized",
Where: "OAuth\xb7PostParams()",
}
}
oParams := o.params()
r, err = o.makeRequest("GET", url, oParams, params)
return
}