aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/test/controller/http_authentication_test.rb
blob: 6f7b31a41b160d474c7588d8af4bd09a75ad9ef0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
require File.dirname(__FILE__) + '/../abstract_unit'

class HttpBasicAuthenticationTest < Test::Unit::TestCase
  include ActionController::HttpAuthentication::Basic
  
  class DummyController
    attr_accessor :headers, :renders, :request
    
    def initialize
      @headers, @renders = {}, []
      @request = ActionController::TestRequest.new
    end
    
    def render(options)
      self.renders << options
    end
  end

  def setup
    @controller  = DummyController.new
    @credentials = ActionController::HttpAuthentication::Basic.encode_credentials("dhh", "secret")
  end

  def test_successful_authentication
    login = Proc.new { |user_name, password| user_name == "dhh" && password == "secret" }
    set_headers
    assert authenticate(@controller, &login)

    set_headers ''
    assert_nothing_raised do
      assert !authenticate(@controller, &login)
    end

    set_headers nil
    set_headers @credentials, 'REDIRECT_X_HTTP_AUTHORIZATION'
    assert authenticate(@controller, &login)
  end

  def test_failing_authentication
    set_headers
    assert !authenticate(@controller) { |user_name, password| user_name == "dhh" && password == "incorrect" }
  end
  
  def test_authentication_request
    authentication_request(@controller, "Megaglobalapp")
    assert_equal 'Basic realm="Megaglobalapp"', @controller.headers["WWW-Authenticate"]
    assert_equal :unauthorized, @controller.renders.first[:status]
  end

  private
    def set_headers(value = @credentials, name = 'HTTP_AUTHORIZATION')
      @controller.request.env[name] = value
    end
end