-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathoauth.go
242 lines (216 loc) · 5.59 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
package smugmug
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"io"
"net/url"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
)
type oauthConf struct {
apiKey string
apiSecret string
userToken string
userSecret string
}
var oauthKeys = []string{
"oauth_consumer_key",
"oauth_nonce",
"oauth_signature",
"oauth_signature_method",
"oauth_timestamp",
"oauth_token",
"oauth_version",
"oauth_callback",
"oauth_verifier",
"oauth_session_handle",
}
var nonceCounter uint64
func init() {
if err := binary.Read(rand.Reader, binary.BigEndian, &nonceCounter); err != nil {
// fallback to time if rand reader is broken
nonceCounter = uint64(time.Now().UnixNano())
}
}
// nonce returns a unique string.
func nonce() string {
return strconv.FormatUint(atomic.AddUint64(&nonceCounter, 1), 16)
}
func newOauthConf(apiKey, apiSecret, userToken, userSecret string) *oauthConf {
return &oauthConf{
apiKey: apiKey,
apiSecret: apiSecret,
userToken: userToken,
userSecret: userSecret,
}
}
func (cfg *oauthConf) authorizationHeader(url string) (string, error) {
var oauthParams = map[string]string{
"oauth_consumer_key": cfg.apiKey,
"oauth_signature_method": "HMAC-SHA1",
"oauth_version": "1.0",
"oauth_token": cfg.userToken,
"oauth_timestamp": strconv.FormatInt(time.Now().Unix(), 10),
"oauth_nonce": nonce(),
}
signature := cfg.getHMACSignature(url, oauthParams)
oauthParams["oauth_signature"] = signature
var h []byte
// Append parameters in a fixed order to support testing.
for _, k := range oauthKeys {
if v, ok := oauthParams[k]; ok {
if h == nil {
h = []byte(`OAuth `)
} else {
h = append(h, ", "...)
}
h = append(h, k...)
h = append(h, `="`...)
h = append(h, encode(v, false)...)
h = append(h, '"')
}
}
return string(h), nil
}
func (cfg *oauthConf) getHMACSignature(urlStr string, oauthParams map[string]string) string {
key := encode(cfg.apiSecret, false)
key = append(key, '&')
u, err := url.Parse(urlStr)
if err != nil {
log.Fatal(err)
}
// if r.credentials != nil {
key = append(key, encode(cfg.userSecret, false)...)
// }
h := hmac.New(sha1.New, key)
writeBaseString(h, "GET", u, url.Values{}, oauthParams)
signature := base64.StdEncoding.EncodeToString(h.Sum(key[:0]))
// return string(rawSignature)
return signature
}
// noscape[b] is true if b should not be escaped per section 3.6 of the RFC.
var noEscape = [256]bool{
'A': true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
'a': true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
'0': true, true, true, true, true, true, true, true, true, true,
'-': true,
'.': true,
'_': true,
'~': true,
}
// encode encodes string per section 3.6 of the RFC. If double is true, then
// the encoding is applied twice.
func encode(s string, double bool) []byte {
// Compute size of result.
m := 3
if double {
m = 5
}
n := 0
for i := 0; i < len(s); i++ {
if noEscape[s[i]] {
n++
} else {
n += m
}
}
p := make([]byte, n)
// Encode it.
j := 0
for i := 0; i < len(s); i++ {
b := s[i]
if noEscape[b] {
p[j] = b
j++
} else if double {
p[j] = '%'
p[j+1] = '2'
p[j+2] = '5'
p[j+3] = "0123456789ABCDEF"[b>>4]
p[j+4] = "0123456789ABCDEF"[b&15]
j += 5
} else {
p[j] = '%'
p[j+1] = "0123456789ABCDEF"[b>>4]
p[j+2] = "0123456789ABCDEF"[b&15]
j += 3
}
}
return p
}
type keyValue struct{ key, value []byte }
type byKeyValue []keyValue
func (p byKeyValue) Len() int { return len(p) }
func (p byKeyValue) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p byKeyValue) Less(i, j int) bool {
sgn := bytes.Compare(p[i].key, p[j].key)
if sgn == 0 {
sgn = bytes.Compare(p[i].value, p[j].value)
}
return sgn < 0
}
func (p byKeyValue) appendValues(values url.Values) byKeyValue {
for k, vs := range values {
k := encode(k, true)
for _, v := range vs {
v := encode(v, true)
p = append(p, keyValue{k, v})
}
}
return p
}
func writeBaseString(w io.Writer, method string, u *url.URL, form url.Values, oauthParams map[string]string) {
// Method
w.Write(encode(strings.ToUpper(method), false))
w.Write([]byte{'&'})
// URL
scheme := strings.ToLower(u.Scheme)
host := strings.ToLower(u.Host)
uNoQuery := *u
uNoQuery.RawQuery = ""
path := uNoQuery.RequestURI()
switch {
case scheme == "http" && strings.HasSuffix(host, ":80"):
host = host[:len(host)-len(":80")]
case scheme == "https" && strings.HasSuffix(host, ":443"):
host = host[:len(host)-len(":443")]
}
w.Write(encode(scheme, false))
w.Write(encode("://", false))
w.Write(encode(host, false))
w.Write(encode(path, false))
w.Write([]byte{'&'})
// Create sorted slice of encoded parameters. Parameter keys and values are
// double encoded in a single step. This is safe because double encoding
// does not change the sort order.
queryParams := u.Query()
p := make(byKeyValue, 0, len(form)+len(queryParams)+len(oauthParams))
p = p.appendValues(form)
p = p.appendValues(queryParams)
for k, v := range oauthParams {
p = append(p, keyValue{encode(k, true), encode(v, true)})
}
sort.Sort(p)
// Write the parameters.
encodedAmp := encode("&", false)
encodedEqual := encode("=", false)
sep := false
for _, kv := range p {
if sep {
w.Write(encodedAmp)
} else {
sep = true
}
w.Write(kv.key)
w.Write(encodedEqual)
w.Write(kv.value)
}
}