Permalink
Browse files

Tons of fixes.

  • Loading branch information...
1 parent 9891340 commit 81f27981e0259431877288d7a606cea844bdce29 @robinator committed Feb 8, 2013
Showing with 24 additions and 7 deletions.
  1. +11 −3 README.md
  2. +10 −1 lib/{rack_simple_auth.rb → rack-simple-auth.rb}
  3. +3 −3 rack-simple-auth.gemspec
View
@@ -7,9 +7,17 @@ A dead simple rack middleware for cookie authentication. This middleware enhanc
For rails, create an initializer file with something like:
MyApp::Application.config.middleware.use Rack::SimpleAuth,
- key: 'your_cookie_key',
- secret: 'my_long_secret',
- login_url: 'http://url_where_user_will_be_redirected_to_authenticate.com'
+ key: 'your_cookie_key', # required
+ secret: 'my_long_secret', # required
+ login_url: 'http://url_where_user_will_be_redirected_to_authenticate.com', # required
+ authenticated_with: Proc.new { |value| true } # optional: must return a boolean
+
+By default, the middleware doesn't actually check the value of the cookie, only that the correct key exists and hasn't been tampered with. You can add more complex rules by passing the `authenticated_with` option with a proc that takes the cookie value as its only argument.
+
+For example:
+
+ # assuming you had a User model and the cookie value is a user_id
+ authenticated_with: Proc.new { |value| user = User.find(value) && user.admin? }
### How it Works
@@ -1,10 +1,14 @@
+require 'rack'
+require 'rack/request'
+
module Rack
class SimpleAuth
def initialize(app, options = {})
@app = app
@key = options[:key]
@secret = options[:secret]
@login_url = options[:login_url]
+ @authenticated_with = options[:authenticated_with] || Proc.new { |value| true }
end
def call(env)
@@ -20,7 +24,12 @@ def authenticated?(cookies)
if data = cookies[@key]
packed_data, digest = data.split('--')
hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, @secret, packed_data)
- digest == hmac # false if tampering going on
+ begin
+ # false if tampering going on
+ digest == hmac && @authenticated_with.call(packed_data.unpack("m*").first)
+ rescue
+ false
+ end
else
false
end
@@ -4,14 +4,14 @@ Gem::Specification.new do |s|
s.date = '2013-02-08'
s.summary = 'A rack middleware for cookie authentication.'
s.description = 'A middleware the prevents access to a rack app without the proper cookie.'
+ s.license = 'MIT'
- s.required_ruby_version = '>= 1.9.2'
+ s.required_ruby_version = '>= 1.9.2'
s.author = 'Rob Law'
s.email = 'rob@robmadethis.com'
s.homepage = 'http://robmadethis.com'
- s.files = Dir['{lib}/*']
-
+ s.files = ['lib/rack-simple-auth.rb', 'README.md']
s.add_dependency 'rack'
end

0 comments on commit 81f2798

Please sign in to comment.