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
|
# File 'lib/om.rb', line 49
def om(consumer, url, post_params, token=nil, method='POST', realm=nil, timestamp=nil, nonce=nil)
method = method.upcase
if post_params.is_a?(Array)
params = post_params
else
params = post_params.collect { |x| x }
end
params = params.collect { |k,v| [k.to_s, v.to_s]}
url = URI.parse(url)
url.scheme = url.scheme.downcase
url.user = url.password = nil
url.host = url.host.downcase
if url.query
CGI.parse(url.query).each { |k,vs| vs.each { |v| params.push([k,v]) } }
end
url.query = nil
url.fragment = nil
params = params + [
['oauth_version', '1.0'],
['oauth_timestamp', timestamp || Time.now.to_i.to_s],
['oauth_nonce', nonce || rand(1000000).to_s],
['oauth_signature_method', 'HMAC-SHA1'],
['oauth_consumer_key', consumer[0]],
]
hmac_key = consumer[1] + '&'
if token != nil
params.push ['oauth_token', token[0]]
hmac_key += token[1]
end
def percent_encode(s)
if s.respond_to?(:encoding)
s = s.encode(Encoding::UTF_8)
else
begin
$__om_utf8_checker.iconv(s)
rescue Iconv::IllegalSequence => exception
throw ArgumentError.new("Non-UTF-8 string: "+s.inspect)
end
end
chars = s.bytes.map do |b|
c = b.chr
if ((c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or
(c >= 'a' and c <= 'z') or
c == '-' or c == '.' or c == '_' or c == '~')
c
else
'%%%02X' % b
end
end
chars.join
end
params.sort!
normalized_params = (params.collect {|p| percent_encode(p[0])+'='+percent_encode(p[1])}).join '&'
signature_base_string = (percent_encode(method) +
'&' + percent_encode(url.to_s) +
'&' + percent_encode(normalized_params))
hmac = Digest::HMAC.new(hmac_key, Digest::SHA1)
hmac.update(signature_base_string)
oauth_signature = [hmac.digest].pack('m0').strip
if realm
authorization_params = [['realm', realm]]
else
authorization_params = []
end
authorization_params.push(['oauth_signature', oauth_signature])
oauth_params = ['oauth_version', 'oauth_timestamp', 'oauth_nonce',
'oauth_signature_method', 'oauth_signature',
'oauth_consumer_key', 'oauth_token']
authorization_params.concat(params.select { |param| nil != oauth_params.index(param[0]) })
return 'OAuth ' + (authorization_params.collect {|param| '%s="%s"' % param}).join(', ')
end
|