2009-12-19 03:16:58 +01:00
|
|
|
require 'rack/auth/basic'
|
|
|
|
require 'rack/mock'
|
|
|
|
|
2010-06-14 06:09:24 +02:00
|
|
|
describe Rack::Auth::Basic do
|
2009-12-19 03:16:58 +01:00
|
|
|
def realm
|
|
|
|
'WallysWorld'
|
|
|
|
end
|
2010-06-14 06:09:24 +02:00
|
|
|
|
2009-12-19 03:16:58 +01:00
|
|
|
def unprotected_app
|
|
|
|
lambda { |env| [ 200, {'Content-Type' => 'text/plain'}, ["Hi #{env['REMOTE_USER']}"] ] }
|
|
|
|
end
|
2010-06-14 06:09:24 +02:00
|
|
|
|
2009-12-19 03:16:58 +01:00
|
|
|
def protected_app
|
|
|
|
app = Rack::Auth::Basic.new(unprotected_app) { |username, password| 'Boss' == username }
|
|
|
|
app.realm = realm
|
|
|
|
app
|
|
|
|
end
|
|
|
|
|
2010-06-14 06:09:24 +02:00
|
|
|
before do
|
2009-12-19 03:16:58 +01:00
|
|
|
@request = Rack::MockRequest.new(protected_app)
|
|
|
|
end
|
|
|
|
|
|
|
|
def request_with_basic_auth(username, password, &block)
|
|
|
|
request 'HTTP_AUTHORIZATION' => 'Basic ' + ["#{username}:#{password}"].pack("m*"), &block
|
|
|
|
end
|
|
|
|
|
|
|
|
def request(headers = {})
|
|
|
|
yield @request.get('/', headers)
|
|
|
|
end
|
|
|
|
|
|
|
|
def assert_basic_auth_challenge(response)
|
|
|
|
response.should.be.a.client_error
|
|
|
|
response.status.should.equal 401
|
|
|
|
response.should.include 'WWW-Authenticate'
|
|
|
|
response.headers['WWW-Authenticate'].should =~ /Basic realm="#{Regexp.escape(realm)}"/
|
|
|
|
response.body.should.be.empty
|
|
|
|
end
|
|
|
|
|
2010-06-14 06:09:24 +02:00
|
|
|
should 'challenge correctly when no credentials are specified' do
|
2009-12-19 03:16:58 +01:00
|
|
|
request do |response|
|
|
|
|
assert_basic_auth_challenge response
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2010-06-14 06:09:24 +02:00
|
|
|
should 'rechallenge if incorrect credentials are specified' do
|
2009-12-19 03:16:58 +01:00
|
|
|
request_with_basic_auth 'joe', 'password' do |response|
|
|
|
|
assert_basic_auth_challenge response
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2010-06-14 06:09:24 +02:00
|
|
|
should 'return application output if correct credentials are specified' do
|
2009-12-19 03:16:58 +01:00
|
|
|
request_with_basic_auth 'Boss', 'password' do |response|
|
|
|
|
response.status.should.equal 200
|
|
|
|
response.body.to_s.should.equal 'Hi Boss'
|
|
|
|
end
|
|
|
|
end
|
2010-06-14 06:09:24 +02:00
|
|
|
|
|
|
|
should 'return 400 Bad Request if different auth scheme used' do
|
2009-12-19 03:16:58 +01:00
|
|
|
request 'HTTP_AUTHORIZATION' => 'Digest params' do |response|
|
|
|
|
response.should.be.a.client_error
|
|
|
|
response.status.should.equal 400
|
|
|
|
response.should.not.include 'WWW-Authenticate'
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2010-06-14 06:09:24 +02:00
|
|
|
it 'takes realm as optional constructor arg' do
|
2009-12-19 03:16:58 +01:00
|
|
|
app = Rack::Auth::Basic.new(unprotected_app, realm) { true }
|
2010-06-14 06:09:24 +02:00
|
|
|
realm.should == app.realm
|
2009-12-19 03:16:58 +01:00
|
|
|
end
|
|
|
|
end
|