auth-hmac 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/History.txt ADDED
@@ -0,0 +1,3 @@
1
+ == 1.0.1 2008-08-11
2
+
3
+ * Initial release
data/License.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 The Kaphan Foundation
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Manifest.txt ADDED
@@ -0,0 +1,21 @@
1
+ History.txt
2
+ License.txt
3
+ Manifest.txt
4
+ PostInstall.txt
5
+ README.txt
6
+ Rakefile
7
+ config/hoe.rb
8
+ config/requirements.rb
9
+ lib/auth-hmac.rb
10
+ lib/auth-hmac/version.rb
11
+ script/console
12
+ script/destroy
13
+ script/generate
14
+ setup.rb
15
+ spec/auth-hmac_spec.rb
16
+ spec/spec.opts
17
+ spec/spec_helper.rb
18
+ tasks/deployment.rake
19
+ tasks/environment.rake
20
+ tasks/rspec.rake
21
+ tasks/website.rake
data/PostInstall.txt ADDED
@@ -0,0 +1,7 @@
1
+
2
+ For more information on auth-hmac, see http://auth-hmac.rubyforge.org
3
+
4
+ NOTE: Change this information in PostInstall.txt
5
+ You can also delete it if you don't want it.
6
+
7
+
data/README.txt ADDED
@@ -0,0 +1,129 @@
1
+ = auth-hmac
2
+
3
+ == What is it?
4
+
5
+ auth-hmac is a Ruby implementation of HMAC[http://en.wikipedia.org/wiki/HMAC] based authentication of HTTP requests.
6
+
7
+ HMAC authentication involves a client and server having a shared secret key. When sending the request the client, signs the request using the secret key. This involves building a canonical representation of the request and then generating a HMAC of the request using the secret. The generated HMAC is then sent as part of the request.
8
+
9
+ When the server receives the request it builds the same canonical representation and generates a HMAC using it's copy of the secret key, if the HMAC produced by the server matches the HMAC sent by the client, the server can be assured that the client also possesses the shared secret key.
10
+
11
+ HMAC based authentication also provides message integrity checking because the HMAC is based on a combination of the shared secret and the content of the request. So if any part of the request that is used to build the canonical representation is modified by a malicious party or in transit the authentication will then fail.
12
+
13
+ AuthHMAC was built to support authentication between various applications build by Peerworks[http://peerworks.org].
14
+
15
+ AuthHMAC is loosely based on the Amazon Web Services authentication scheme but without the Amazon specific components, i.e. it is HMAC for the rest of us.
16
+
17
+ == What does it require?
18
+
19
+ AuthHMAC requires Ruby's OpenSSL support. This should be standard in most Ruby builds.
20
+
21
+ == When to use it?
22
+
23
+ HMAC Authentication is best used as authentication for communication between applications such as web services. It provides better security than HTTP Basic authentication without the need to set up SSL. Of course if you need to protect the confidentiality of the data then you need SSL, but if you just want to authenticate requests without sending credentials in the clear AuthHMAC is a good choice.
24
+
25
+ == How to use it?
26
+
27
+ The simplest way to use AuthHMAC is with the AuthHMAC.sign! and AuthHMAC#authenticate? methods.
28
+
29
+ AuthHMAC.sign! takes a HTTP request object, an access id and a secret key and signs the request with the access_id and secret key.
30
+
31
+ * The HTTP request object can be a Net::HTTP::HTTPRequest object, a CGI::Request object or a Webrick HTTP request object. AuthHMAC will do its best to figure out which type it is an handle it accordingly.
32
+ * The access_id is used to identify the secret key that was used to sign the request. Think of it as like a user name, it allows you to hand out different keys to different clients and authenticate each of them individually. The access_id is sent in the clear so you should avoid making it an important string.
33
+ * The secret key is the shared secret between the client and the server. You should make this sufficiently random so that is can't be guessed or exposed to dictionary attacks. The follow code will give you a pretty good secret key:
34
+
35
+ random = File.read('/dev/random', 512)
36
+ secret_key = Base64.encode64(Digest::SHA2.new(512).digest(random))
37
+
38
+ On the server side you can then authenticate these requests using the AuthHMAC.authenticated? method. This takes the same arguments as the sign! method but returns true if the request has been signed with the access id and secret or false if it hasn't.
39
+
40
+ If you have more than one set of credentials you might find it useful to create an instance of the AuthHMAC class, passing your credentials as a Hash of access id => secret keys, like so:
41
+
42
+ @authhmac = AuthHMAC.new('access_id1' => 'secret1', 'access_id2' => 'secret2')
43
+
44
+ You can then use the instance methods of the @authhmac object to sign and authenticate requests, for example:
45
+
46
+ @authhmac.sign!(request, "access_id1")
47
+
48
+ will sign +request+ with "access_id1" and it's corresponding secret key. Similarly authentication is done like so:
49
+
50
+ @authhmac.authenticated?(request)
51
+
52
+ which will return true if the request has been signed with one of the access id and secret key pairs provided in the constructor.
53
+
54
+ === Rails Integration
55
+
56
+ AuthHMAC supports authentication within Rails controllers and signing of requests generated by Active Resource. See AuthHMAC::Rails::ControllerFilter::ClassMethods and AuthHMAC::Rails::ActiveResourceExtension::BaseHmac::ClassMethods for details.
57
+
58
+ == How does it work?
59
+
60
+ When creating a signature for a HTTP request AuthHMAC first generates a canonical representation of the request.
61
+
62
+ This canonical string is created like so:
63
+
64
+ canonical_string = HTTP-Verb + "\n" +
65
+ Content-Type + "\n" +
66
+ Content-MD5 + "\n" +
67
+ Date + "\n" +
68
+ request-uri;
69
+
70
+ Where Content-Type, Content-MD5 and Date are all taken from the headers of the request. If Content-Type or Content-MD5 are not present, they are substituted with an empty string. If Date is not present it is added to the request headers with the value +Time.now.httpdate+. +request-uri+ is the path component of the request, without any query string, i.e. everything up to the ?.
71
+
72
+ This string is then used with the secret to generate a SHA1 HMAC using the following:
73
+
74
+ OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), secret_key, canonical_string)
75
+
76
+ The result is then Base64 encoded and added to the headers of the request as the +Authorization+ header in the format:
77
+
78
+ Authorization: AuthHMAC <access_id>:<base64 encoded hmac>
79
+
80
+ When authenaticating a request, AuthHMAC looks for the Authorization header in the above format, parses out the components, regenerates a HMAC for the request, using the secret key identified by the access id and then compares the generated HMAC with the one provided by the client. If they match the request is authenticated.
81
+
82
+ Using these details it is possible to build code that will sign and authenticate AuthHMAC style requests in other languages.
83
+
84
+ == INSTALL:
85
+
86
+ * sudo gem install auth-hmac
87
+
88
+ == Source Code
89
+
90
+ The source repository is accessible via GitHub or Ruby Forge:
91
+
92
+ git clone git://github.com/seangeo/auth-hmac.git
93
+
94
+
95
+ git clone git://rubyforge.org/auth-hmac.git
96
+
97
+ == Contact Information
98
+
99
+ The project page is at http://rubyforge.org/projects/auth-hmac. Please file any bugs or feedback
100
+ using the trackers and forums there.
101
+
102
+ == Authors and Contributors
103
+
104
+ rAtom was developed by Peerworks[http://peerworks.org] and written by Sean Geoghegan.
105
+
106
+ == LICENSE:
107
+
108
+ (The MIT License)
109
+
110
+ Copyright (c) 2008 The Kaphan Foundation
111
+
112
+ Permission is hereby granted, free of charge, to any person obtaining
113
+ a copy of this software and associated documentation files (the
114
+ 'Software'), to deal in the Software without restriction, including
115
+ without limitation the rights to use, copy, modify, merge, publish,
116
+ distribute, sublicense, and/or sell copies of the Software, and to
117
+ permit persons to whom the Software is furnished to do so, subject to
118
+ the following conditions:
119
+
120
+ The above copyright notice and this permission notice shall be
121
+ included in all copies or substantial portions of the Software.
122
+
123
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
124
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
125
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
126
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
127
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
128
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
129
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ require 'config/requirements'
2
+ require 'config/hoe' # setup Hoe + all gem configuration
3
+
4
+ Dir['tasks/**/*.rake'].each { |rake| load rake }
data/config/hoe.rb ADDED
@@ -0,0 +1,73 @@
1
+ require 'auth-hmac/version'
2
+
3
+ AUTHOR = 'Sean Geoghegan' # can also be an array of Authors
4
+ EMAIL = "seangeo@gmail.com"
5
+ DESCRIPTION = "A gem providing HMAC based authentication for HTTP"
6
+ GEM_NAME = 'auth-hmac' # what ppl will type to install your gem
7
+ RUBYFORGE_PROJECT = 'auth-hmac' # The unix name for your project
8
+ HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org"
9
+ DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
10
+ EXTRA_DEPENDENCIES = [
11
+ # ['activesupport', '>= 1.3.1']
12
+ ] # An array of rubygem dependencies [name, version]
13
+
14
+ @config_file = "~/.rubyforge/user-config.yml"
15
+ @config = nil
16
+ RUBYFORGE_USERNAME = "unknown"
17
+ def rubyforge_username
18
+ unless @config
19
+ begin
20
+ @config = YAML.load(File.read(File.expand_path(@config_file)))
21
+ rescue
22
+ puts <<-EOS
23
+ ERROR: No rubyforge config file found: #{@config_file}
24
+ Run 'rubyforge setup' to prepare your env for access to Rubyforge
25
+ - See http://newgem.rubyforge.org/rubyforge.html for more details
26
+ EOS
27
+ exit
28
+ end
29
+ end
30
+ RUBYFORGE_USERNAME.replace @config["username"]
31
+ end
32
+
33
+
34
+ REV = nil
35
+ # UNCOMMENT IF REQUIRED:
36
+ # REV = YAML.load(`svn info`)['Revision']
37
+ VERS = AuthHMAC::VERSION::STRING + (REV ? ".#{REV}" : "")
38
+ RDOC_OPTS = ['--quiet', '--title', 'auth-hmac documentation',
39
+ "--opname", "index.html",
40
+ "--line-numbers",
41
+ "--main", "README",
42
+ "--inline-source"]
43
+
44
+ class Hoe
45
+ def extra_deps
46
+ @extra_deps.reject! { |x| Array(x).first == 'hoe' }
47
+ @extra_deps
48
+ end
49
+ end
50
+
51
+ # Generate all the Rake tasks
52
+ # Run 'rake -T' to see list of generated tasks (from gem root directory)
53
+ $hoe = Hoe.new(GEM_NAME, VERS) do |p|
54
+ p.developer(AUTHOR, EMAIL)
55
+ p.description = DESCRIPTION
56
+ p.summary = DESCRIPTION
57
+ p.url = HOMEPATH
58
+ p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
59
+ p.test_globs = ["test/**/test_*.rb"]
60
+ p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean.
61
+
62
+ # == Optional
63
+ p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
64
+ #p.extra_deps = EXTRA_DEPENDENCIES
65
+
66
+ #p.spec_extras = {} # A hash of extra values to set in the gemspec.
67
+ end
68
+
69
+ CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n")
70
+ PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
71
+ $hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''))
72
+ $hoe.rsync_args = '-av --delete --ignore-errors'
73
+ $hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue ""
@@ -0,0 +1,15 @@
1
+ require 'fileutils'
2
+ include FileUtils
3
+
4
+ require 'rubygems'
5
+ %w[rake hoe newgem rubigen].each do |req_gem|
6
+ begin
7
+ require req_gem
8
+ rescue LoadError
9
+ puts "This Rakefile requires the '#{req_gem}' RubyGem."
10
+ puts "Installation: gem install #{req_gem} -y"
11
+ exit
12
+ end
13
+ end
14
+
15
+ $:.unshift(File.join(File.dirname(__FILE__), %w[.. lib]))
data/lib/auth-hmac.rb ADDED
@@ -0,0 +1,335 @@
1
+ # Copyright (c) 2008 The Kaphan Foundation
2
+ #
3
+ # See License.txt for licensing information.
4
+ #
5
+
6
+ $:.unshift(File.dirname(__FILE__)) unless
7
+ $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
8
+
9
+ require 'openssl'
10
+ require 'base64'
11
+
12
+ # This module provides a HMAC Authentication method for HTTP requests. It should work with
13
+ # net/http request classes and CGIRequest classes and hence Rails.
14
+ #
15
+ # It is loosely based on the Amazon Web Services Authentication mechanism but
16
+ # generalized to be useful to any application that requires HMAC based authentication.
17
+ # As a result of the generalization, it won't work with AWS because it doesn't support
18
+ # the Amazon extension headers.
19
+ #
20
+ class AuthHMAC
21
+ module Headers # :nodoc:
22
+ # Gets the headers for a request.
23
+ #
24
+ # Attempts to deal with known HTTP header representations in Ruby.
25
+ # Currently handles net/http and Rails.
26
+ #
27
+ def headers(request)
28
+ if request.respond_to?(:[])
29
+ request
30
+ elsif request.respond_to?(:headers)
31
+ request.headers
32
+ else
33
+ raise ArgumentError, "Don't know how to get the headers from #{request.inspect}"
34
+ end
35
+ end
36
+
37
+ def find_header(keys, headers)
38
+ keys.map do |key|
39
+ headers[key]
40
+ end.compact.first
41
+ end
42
+ end
43
+
44
+ include Headers
45
+
46
+ # Signs a request using a given access key id and secret.
47
+ #
48
+ def AuthHMAC.sign!(request, access_key_id, secret)
49
+ self.new(access_key_id => secret).sign!(request, access_key_id)
50
+ end
51
+
52
+ def AuthHMAC.authenticated?(request, access_key_id, secret)
53
+ self.new(access_key_id => secret).authenticated?(request)
54
+ end
55
+
56
+ # Create an AuthHMAC instance using a given credential store.
57
+ #
58
+ # A credential store must respond to the [] method and return
59
+ # the secret for the access key id passed to [].
60
+ #
61
+ def initialize(credential_store)
62
+ @credential_store = credential_store
63
+ end
64
+
65
+ # Signs a request using the access_key_id and the secret associated with that id
66
+ # in the credential store.
67
+ #
68
+ # Signing a requests adds an Authorization header to the request in the format:
69
+ #
70
+ # AuthHMAC <access_key_id>:<signature>
71
+ #
72
+ # where <signature> is the Base64 encoded HMAC-SHA1 of the CanonicalString and the secret.
73
+ #
74
+ def sign!(request, access_key_id)
75
+ secret = @credential_store[access_key_id]
76
+ raise ArgumentError, "No secret found for key id '#{access_key_id}'" if secret.nil?
77
+ request['Authorization'] = build_authorization_header(request, access_key_id, secret)
78
+ end
79
+
80
+ # Authenticates a request using HMAC
81
+ #
82
+ # Returns true if the request has an AuthHMAC Authorization header and
83
+ # the access id and HMAC match an id and HMAC produced for the secret
84
+ # in the credential store. Otherwise returns false.
85
+ #
86
+ def authenticated?(request)
87
+ if md = /^AuthHMAC ([^:]+):(.+)$/.match(find_header(%w(Authorization HTTP_AUTHORIZATION), headers(request)))
88
+ access_key_id = md[1]
89
+ hmac = md[2]
90
+ secret = @credential_store[access_key_id]
91
+ !secret.nil? && hmac == build_signature(request, secret)
92
+ else
93
+ false
94
+ end
95
+ end
96
+
97
+ private
98
+ def build_authorization_header(request, access_key_id, secret)
99
+ "AuthHMAC #{access_key_id}:#{build_signature(request, secret)}"
100
+ end
101
+
102
+ def build_signature(request, secret)
103
+ canonical_string = CanonicalString.new(request)
104
+ digest = OpenSSL::Digest::Digest.new('sha1')
105
+ Base64.encode64(OpenSSL::HMAC.digest(digest, secret, canonical_string)).strip
106
+ end
107
+
108
+ # Build a Canonical String for a HTTP request.
109
+ #
110
+ # A Canonical String has the following format:
111
+ #
112
+ # CanonicalString = HTTP-Verb + "\n" +
113
+ # Content-Type + "\n" +
114
+ # Content-MD5 + "\n" +
115
+ # Date + "\n" +
116
+ # request-uri;
117
+ #
118
+ #
119
+ # If the Date header doesn't exist, one will be generated since
120
+ # Net/HTTP will generate one if it doesn't exist and it will be
121
+ # used on the server side to do authentication.
122
+ #
123
+ class CanonicalString < String # :nodoc:
124
+ include Headers
125
+
126
+ def initialize(request)
127
+ self << request_method(request) + "\n"
128
+ self << header_values(headers(request)) + "\n"
129
+ self << request_path(request)
130
+ end
131
+
132
+ private
133
+ def request_method(request)
134
+ if request.respond_to?(:request_method) && request.request_method.is_a?(String)
135
+ request.request_method
136
+ elsif request.respond_to?(:method) && request.method.is_a?(String)
137
+ request.method
138
+ elsif request.respond_to?(:env) && request.env
139
+ request.env['REQUEST_METHOD']
140
+ else
141
+ raise ArgumentError, "Don't know how to get the request method from #{request.inspect}"
142
+ end
143
+ end
144
+
145
+ def header_values(headers)
146
+ [ content_type(headers),
147
+ content_md5(headers),
148
+ (date(headers) or headers['Date'] = Time.now.getutc.httpdate)
149
+ ].join("\n")
150
+ end
151
+
152
+ def content_type(headers)
153
+ find_header(%w(CONTENT-TYPE CONTENT_TYPE HTTP_CONTENT_TYPE), headers)
154
+ end
155
+
156
+ def date(headers)
157
+ find_header(%w(DATE HTTP_DATE), headers)
158
+ end
159
+
160
+ def content_md5(headers)
161
+ find_header(%w(CONTENT-MD5 CONTENT_MD5), headers)
162
+ end
163
+
164
+ def request_path(request)
165
+ # Try unparsed_uri in case it is a Webrick request
166
+ path = if request.respond_to?(:unparsed_uri)
167
+ request.unparsed_uri
168
+ else
169
+ request.path
170
+ end
171
+
172
+ path[/^[^?]*/]
173
+ end
174
+ end
175
+
176
+ # Integration with Rails
177
+ #
178
+ class Rails # :nodoc:
179
+ module ControllerFilter # :nodoc:
180
+ module ClassMethods
181
+ # Call within a Rails Controller to initialize HMAC authentication for the controller.
182
+ #
183
+ # * +credentials+ must be a hash that indexes secrets by their access key id.
184
+ # * +options+ supports the following arguments:
185
+ # * +failure_message+: The text to use when authentication fails.
186
+ # * +only+: A list off actions to protect.
187
+ # * +except+: A list of actions to not protect.
188
+ #
189
+ def with_auth_hmac(credentials, options = {})
190
+ unless credentials.nil?
191
+ self.credentials = credentials
192
+ self.authhmac = AuthHMAC.new(self.credentials)
193
+ self.authhmac_failure_message = (options.delete(:failure_message) or "HMAC Authentication failed")
194
+ before_filter(:hmac_login_required, options)
195
+ else
196
+ $stderr << "with_auth_hmac called with nil credentials - authentication will be skipped\n"
197
+ end
198
+ end
199
+ end
200
+
201
+ module InstanceMethods # :nodoc:
202
+ def hmac_login_required
203
+ unless hmac_authenticated?
204
+ response.headers['WWW-Authenticate'] = 'AuthHMAC'
205
+ render :text => self.class.authhmac_failure_message, :status => :unauthorized
206
+ end
207
+ end
208
+
209
+ def hmac_authenticated?
210
+ self.class.authhmac.authenticated?(request)
211
+ end
212
+ end
213
+
214
+ unless defined?(ActionController)
215
+ begin
216
+ require 'rubygems'
217
+ gem 'actionpack'
218
+ gem 'activesupport'
219
+ require 'action_controller'
220
+ require 'active_support'
221
+ rescue
222
+ nil
223
+ end
224
+ end
225
+
226
+ if defined?(ActionController::Base)
227
+ ActionController::Base.class_eval do
228
+ class_inheritable_accessor :authhmac
229
+ class_inheritable_accessor :credentials
230
+ class_inheritable_accessor :authhmac_failure_message
231
+ end
232
+
233
+ ActionController::Base.send(:include, ControllerFilter::InstanceMethods)
234
+ ActionController::Base.extend(ControllerFilter::ClassMethods)
235
+ end
236
+ end
237
+
238
+ module ActiveResourceExtension # :nodoc:
239
+ module BaseHmac # :nodoc:
240
+ def self.included(base)
241
+ base.extend(ClassMethods)
242
+
243
+ base.class_inheritable_accessor :hmac_access_id
244
+ base.class_inheritable_accessor :hmac_secret
245
+ base.class_inheritable_accessor :use_hmac
246
+ end
247
+
248
+ module ClassMethods
249
+ # Call with an Active Resource class definition to sign
250
+ # all HTTP requests sent by that class with the provided
251
+ # credentials.
252
+ #
253
+ # Can be called with either a hash or two separate parameters
254
+ # like so:
255
+ #
256
+ # class MyResource < ActiveResource::Base
257
+ # with_auth_hmac("my_access_id", "my_secret")
258
+ # end
259
+ #
260
+ # or
261
+ #
262
+ # class MyOtherResource < ActiveResource::Base
263
+ # with_auth_hmac("my_access_id" => "my_secret")
264
+ # end
265
+ #
266
+ #
267
+ # This has only been tested with Rails 2.1 and since it is virtually a monkey
268
+ # patch of the internals of ActiveResource it might not work with past or
269
+ # future versions.
270
+ #
271
+ def with_auth_hmac(access_id, secret = nil)
272
+ if access_id.is_a?(Hash)
273
+ self.hmac_access_id = access_id.keys.first
274
+ self.hmac_secret = access_id[self.hmac_access_id]
275
+ else
276
+ self.hmac_access_id = access_id
277
+ self.hmac_secret = secret
278
+ end
279
+ self.use_hmac = true
280
+
281
+ class << self
282
+ alias_method_chain :connection, :hmac
283
+ end
284
+ end
285
+
286
+ def connection_with_hmac(refresh = false) # :nodoc:
287
+ c = connection_without_hmac(refresh)
288
+ c.hmac_access_id = self.hmac_access_id
289
+ c.hmac_secret = self.hmac_secret
290
+ c.use_hmac = self.use_hmac
291
+ c
292
+ end
293
+ end
294
+
295
+ module InstanceMethods # :nodoc:
296
+ end
297
+ end
298
+
299
+ module Connection # :nodoc:
300
+ def self.included(base)
301
+ base.send :alias_method_chain, :request, :hmac
302
+ base.class_eval do
303
+ attr_accessor :hmac_secret, :hmac_access_id, :use_hmac
304
+ end
305
+ end
306
+
307
+ def request_with_hmac(method, path, *arguments)
308
+ if use_hmac && hmac_access_id && hmac_secret
309
+ arguments.last['Date'] = Time.now.httpdate if arguments.last['Date'].nil?
310
+ temp = "Net::HTTP::#{method.to_s.capitalize}".constantize.new(path, arguments.last)
311
+ AuthHMAC.sign!(temp, hmac_access_id, hmac_secret)
312
+ arguments.last['Authorization'] = temp['Authorization']
313
+ end
314
+
315
+ request_without_hmac(method, path, *arguments)
316
+ end
317
+ end
318
+
319
+ unless defined?(ActiveResource)
320
+ begin
321
+ require 'rubygems'
322
+ gem 'activeresource'
323
+ require 'activeresource'
324
+ rescue
325
+ nil
326
+ end
327
+ end
328
+
329
+ if defined?(ActiveResource)
330
+ ActiveResource::Base.send(:include, BaseHmac)
331
+ ActiveResource::Connection.send(:include, Connection)
332
+ end
333
+ end
334
+ end
335
+ end