Class: Rack::SimpleAuth

Inherits:
Object
  • Object
show all
Defined in:
lib/rack-simple-auth.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ SimpleAuth

Returns a new instance of SimpleAuth.



5
6
7
8
9
10
11
12
# File 'lib/rack-simple-auth.rb', line 5

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 }
  @except = options[:except] || Proc.new { false }
end

Instance Method Details

#authenticated?(cookies) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rack-simple-auth.rb', line 23

def authenticated?(cookies)
  if data = cookies[@key]
    packed_data, digest = data.split('--')
    hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, @secret, packed_data)
    begin
      # false if tampering going on
      digest == hmac && @authenticated_with.call(packed_data.unpack("m*").first)
    rescue
      false
    end
  else
    false
  end
end

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/rack-simple-auth.rb', line 14

def call(env)
  request = Request.new(env)
  if authenticated?(request.cookies) || @except.call(request)
    @app.call(env)
  else
    [302, {'Content-Type' => 'text/plain', 'Location' => "#{@login_url}?return_to=#{request.url}"}, ['You must be logged in to see this.']]
  end
end