Updated README.rdoc again
[feedcatcher.git] / vendor / rails / actionpack / test / controller / http_basic_authentication_test.rb
1 require 'abstract_unit'
2
3 class HttpBasicAuthenticationTest < ActionController::TestCase
4 class DummyController < ActionController::Base
5 before_filter :authenticate, :only => :index
6 before_filter :authenticate_with_request, :only => :display
7
8 def index
9 render :text => "Hello Secret"
10 end
11
12 def display
13 render :text => 'Definitely Maybe'
14 end
15
16 private
17
18 def authenticate
19 authenticate_or_request_with_http_basic do |username, password|
20 username == 'lifo' && password == 'world'
21 end
22 end
23
24 def authenticate_with_request
25 if authenticate_with_http_basic { |username, password| username == 'pretty' && password == 'please' }
26 @logged_in = true
27 else
28 request_http_basic_authentication("SuperSecret")
29 end
30 end
31 end
32
33 AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION']
34
35 tests DummyController
36
37 AUTH_HEADERS.each do |header|
38 test "successful authentication with #{header.downcase}" do
39 @request.env[header] = encode_credentials('lifo', 'world')
40 get :index
41
42 assert_response :success
43 assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}"
44 end
45 end
46
47 AUTH_HEADERS.each do |header|
48 test "unsuccessful authentication with #{header.downcase}" do
49 @request.env[header] = encode_credentials('h4x0r', 'world')
50 get :index
51
52 assert_response :unauthorized
53 assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}"
54 end
55 end
56
57 test "authentication request without credential" do
58 get :display
59
60 assert_response :unauthorized
61 assert_equal "HTTP Basic: Access denied.\n", @response.body
62 assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate']
63 end
64
65 test "authentication request with invalid credential" do
66 @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'foo')
67 get :display
68
69 assert_response :unauthorized
70 assert_equal "HTTP Basic: Access denied.\n", @response.body
71 assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate']
72 end
73
74 test "authentication request with valid credential" do
75 @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'please')
76 get :display
77
78 assert_response :success
79 assert assigns(:logged_in)
80 assert_equal 'Definitely Maybe', @response.body
81 end
82
83 private
84
85 def encode_credentials(username, password)
86 "Basic #{ActiveSupport::Base64.encode64("#{username}:#{password}")}"
87 end
88 end