halorgium-actionpack 3.0.pre

Sign up to get free protection for your applications and to get access to all the features.
Files changed (154) hide show
  1. data/CHANGELOG +5179 -0
  2. data/MIT-LICENSE +21 -0
  3. data/README +409 -0
  4. data/lib/abstract_controller.rb +16 -0
  5. data/lib/abstract_controller/base.rb +158 -0
  6. data/lib/abstract_controller/callbacks.rb +113 -0
  7. data/lib/abstract_controller/exceptions.rb +12 -0
  8. data/lib/abstract_controller/helpers.rb +151 -0
  9. data/lib/abstract_controller/layouts.rb +250 -0
  10. data/lib/abstract_controller/localized_cache.rb +49 -0
  11. data/lib/abstract_controller/logger.rb +61 -0
  12. data/lib/abstract_controller/rendering_controller.rb +188 -0
  13. data/lib/action_controller.rb +72 -0
  14. data/lib/action_controller/base.rb +168 -0
  15. data/lib/action_controller/caching.rb +80 -0
  16. data/lib/action_controller/caching/actions.rb +163 -0
  17. data/lib/action_controller/caching/fragments.rb +116 -0
  18. data/lib/action_controller/caching/pages.rb +154 -0
  19. data/lib/action_controller/caching/sweeping.rb +97 -0
  20. data/lib/action_controller/deprecated.rb +4 -0
  21. data/lib/action_controller/deprecated/integration_test.rb +2 -0
  22. data/lib/action_controller/deprecated/performance_test.rb +1 -0
  23. data/lib/action_controller/dispatch/dispatcher.rb +57 -0
  24. data/lib/action_controller/metal.rb +129 -0
  25. data/lib/action_controller/metal/benchmarking.rb +73 -0
  26. data/lib/action_controller/metal/compatibility.rb +145 -0
  27. data/lib/action_controller/metal/conditional_get.rb +86 -0
  28. data/lib/action_controller/metal/configuration.rb +28 -0
  29. data/lib/action_controller/metal/cookies.rb +105 -0
  30. data/lib/action_controller/metal/exceptions.rb +55 -0
  31. data/lib/action_controller/metal/filter_parameter_logging.rb +77 -0
  32. data/lib/action_controller/metal/flash.rb +162 -0
  33. data/lib/action_controller/metal/head.rb +27 -0
  34. data/lib/action_controller/metal/helpers.rb +115 -0
  35. data/lib/action_controller/metal/hide_actions.rb +47 -0
  36. data/lib/action_controller/metal/http_authentication.rb +312 -0
  37. data/lib/action_controller/metal/layouts.rb +171 -0
  38. data/lib/action_controller/metal/mime_responds.rb +317 -0
  39. data/lib/action_controller/metal/rack_convenience.rb +27 -0
  40. data/lib/action_controller/metal/redirector.rb +22 -0
  41. data/lib/action_controller/metal/render_options.rb +103 -0
  42. data/lib/action_controller/metal/rendering_controller.rb +57 -0
  43. data/lib/action_controller/metal/request_forgery_protection.rb +108 -0
  44. data/lib/action_controller/metal/rescuable.rb +13 -0
  45. data/lib/action_controller/metal/responder.rb +200 -0
  46. data/lib/action_controller/metal/session.rb +15 -0
  47. data/lib/action_controller/metal/session_management.rb +45 -0
  48. data/lib/action_controller/metal/streaming.rb +188 -0
  49. data/lib/action_controller/metal/testing.rb +39 -0
  50. data/lib/action_controller/metal/url_for.rb +41 -0
  51. data/lib/action_controller/metal/verification.rb +130 -0
  52. data/lib/action_controller/middleware.rb +38 -0
  53. data/lib/action_controller/notifications.rb +10 -0
  54. data/lib/action_controller/polymorphic_routes.rb +183 -0
  55. data/lib/action_controller/record_identifier.rb +91 -0
  56. data/lib/action_controller/testing/process.rb +111 -0
  57. data/lib/action_controller/testing/test_case.rb +345 -0
  58. data/lib/action_controller/translation.rb +13 -0
  59. data/lib/action_controller/url_rewriter.rb +204 -0
  60. data/lib/action_controller/vendor/html-scanner.rb +16 -0
  61. data/lib/action_controller/vendor/html-scanner/html/document.rb +68 -0
  62. data/lib/action_controller/vendor/html-scanner/html/node.rb +537 -0
  63. data/lib/action_controller/vendor/html-scanner/html/sanitizer.rb +176 -0
  64. data/lib/action_controller/vendor/html-scanner/html/selector.rb +828 -0
  65. data/lib/action_controller/vendor/html-scanner/html/tokenizer.rb +105 -0
  66. data/lib/action_controller/vendor/html-scanner/html/version.rb +11 -0
  67. data/lib/action_dispatch.rb +70 -0
  68. data/lib/action_dispatch/http/headers.rb +33 -0
  69. data/lib/action_dispatch/http/mime_type.rb +231 -0
  70. data/lib/action_dispatch/http/mime_types.rb +23 -0
  71. data/lib/action_dispatch/http/request.rb +539 -0
  72. data/lib/action_dispatch/http/response.rb +290 -0
  73. data/lib/action_dispatch/http/status_codes.rb +42 -0
  74. data/lib/action_dispatch/http/utils.rb +20 -0
  75. data/lib/action_dispatch/middleware/callbacks.rb +50 -0
  76. data/lib/action_dispatch/middleware/params_parser.rb +79 -0
  77. data/lib/action_dispatch/middleware/rescue.rb +26 -0
  78. data/lib/action_dispatch/middleware/session/abstract_store.rb +208 -0
  79. data/lib/action_dispatch/middleware/session/cookie_store.rb +235 -0
  80. data/lib/action_dispatch/middleware/session/mem_cache_store.rb +47 -0
  81. data/lib/action_dispatch/middleware/show_exceptions.rb +143 -0
  82. data/lib/action_dispatch/middleware/stack.rb +116 -0
  83. data/lib/action_dispatch/middleware/static.rb +44 -0
  84. data/lib/action_dispatch/middleware/string_coercion.rb +29 -0
  85. data/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb +24 -0
  86. data/lib/action_dispatch/middleware/templates/rescues/_trace.erb +26 -0
  87. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb +10 -0
  88. data/lib/action_dispatch/middleware/templates/rescues/layout.erb +29 -0
  89. data/lib/action_dispatch/middleware/templates/rescues/missing_template.erb +2 -0
  90. data/lib/action_dispatch/middleware/templates/rescues/routing_error.erb +10 -0
  91. data/lib/action_dispatch/middleware/templates/rescues/template_error.erb +21 -0
  92. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.erb +2 -0
  93. data/lib/action_dispatch/routing.rb +381 -0
  94. data/lib/action_dispatch/routing/deprecated_mapper.rb +878 -0
  95. data/lib/action_dispatch/routing/mapper.rb +327 -0
  96. data/lib/action_dispatch/routing/route.rb +49 -0
  97. data/lib/action_dispatch/routing/route_set.rb +497 -0
  98. data/lib/action_dispatch/testing/assertions.rb +8 -0
  99. data/lib/action_dispatch/testing/assertions/dom.rb +35 -0
  100. data/lib/action_dispatch/testing/assertions/model.rb +19 -0
  101. data/lib/action_dispatch/testing/assertions/response.rb +145 -0
  102. data/lib/action_dispatch/testing/assertions/routing.rb +144 -0
  103. data/lib/action_dispatch/testing/assertions/selector.rb +639 -0
  104. data/lib/action_dispatch/testing/assertions/tag.rb +123 -0
  105. data/lib/action_dispatch/testing/integration.rb +504 -0
  106. data/lib/action_dispatch/testing/performance_test.rb +15 -0
  107. data/lib/action_dispatch/testing/test_request.rb +83 -0
  108. data/lib/action_dispatch/testing/test_response.rb +131 -0
  109. data/lib/action_pack.rb +24 -0
  110. data/lib/action_pack/version.rb +9 -0
  111. data/lib/action_view.rb +58 -0
  112. data/lib/action_view/base.rb +308 -0
  113. data/lib/action_view/context.rb +44 -0
  114. data/lib/action_view/erb/util.rb +48 -0
  115. data/lib/action_view/helpers.rb +62 -0
  116. data/lib/action_view/helpers/active_model_helper.rb +306 -0
  117. data/lib/action_view/helpers/ajax_helper.rb +68 -0
  118. data/lib/action_view/helpers/asset_tag_helper.rb +830 -0
  119. data/lib/action_view/helpers/atom_feed_helper.rb +198 -0
  120. data/lib/action_view/helpers/cache_helper.rb +39 -0
  121. data/lib/action_view/helpers/capture_helper.rb +168 -0
  122. data/lib/action_view/helpers/date_helper.rb +988 -0
  123. data/lib/action_view/helpers/debug_helper.rb +38 -0
  124. data/lib/action_view/helpers/form_helper.rb +1102 -0
  125. data/lib/action_view/helpers/form_options_helper.rb +600 -0
  126. data/lib/action_view/helpers/form_tag_helper.rb +495 -0
  127. data/lib/action_view/helpers/javascript_helper.rb +208 -0
  128. data/lib/action_view/helpers/number_helper.rb +311 -0
  129. data/lib/action_view/helpers/prototype_helper.rb +1309 -0
  130. data/lib/action_view/helpers/raw_output_helper.rb +9 -0
  131. data/lib/action_view/helpers/record_identification_helper.rb +20 -0
  132. data/lib/action_view/helpers/record_tag_helper.rb +58 -0
  133. data/lib/action_view/helpers/sanitize_helper.rb +259 -0
  134. data/lib/action_view/helpers/scriptaculous_helper.rb +226 -0
  135. data/lib/action_view/helpers/tag_helper.rb +151 -0
  136. data/lib/action_view/helpers/text_helper.rb +594 -0
  137. data/lib/action_view/helpers/translation_helper.rb +39 -0
  138. data/lib/action_view/helpers/url_helper.rb +639 -0
  139. data/lib/action_view/locale/en.yml +117 -0
  140. data/lib/action_view/paths.rb +80 -0
  141. data/lib/action_view/render/partials.rb +342 -0
  142. data/lib/action_view/render/rendering.rb +134 -0
  143. data/lib/action_view/safe_buffer.rb +28 -0
  144. data/lib/action_view/template/error.rb +101 -0
  145. data/lib/action_view/template/handler.rb +36 -0
  146. data/lib/action_view/template/handlers.rb +52 -0
  147. data/lib/action_view/template/handlers/builder.rb +17 -0
  148. data/lib/action_view/template/handlers/erb.rb +53 -0
  149. data/lib/action_view/template/handlers/rjs.rb +18 -0
  150. data/lib/action_view/template/resolver.rb +165 -0
  151. data/lib/action_view/template/template.rb +131 -0
  152. data/lib/action_view/template/text.rb +38 -0
  153. data/lib/action_view/test_case.rb +163 -0
  154. metadata +236 -0
@@ -0,0 +1,27 @@
1
+ module ActionController
2
+ module Head
3
+ # Return a response that has no content (merely headers). The options
4
+ # argument is interpreted to be a hash of header names and values.
5
+ # This allows you to easily return a response that consists only of
6
+ # significant headers:
7
+ #
8
+ # head :created, :location => person_path(@person)
9
+ #
10
+ # It can also be used to return exceptional conditions:
11
+ #
12
+ # return head(:method_not_allowed) unless request.post?
13
+ # return head(:bad_request) unless valid_request?
14
+ # render
15
+ def head(status, options = {})
16
+ options, status = status, nil if status.is_a?(Hash)
17
+ status ||= options.delete(:status) || :ok
18
+ location = options.delete(:location)
19
+
20
+ options.each do |key, value|
21
+ headers[key.to_s.dasherize.split(/-/).map { |v| v.capitalize }.join("-")] = value.to_s
22
+ end
23
+
24
+ render :nothing => true, :status => status, :location => location
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,115 @@
1
+ module ActionController
2
+ # The Rails framework provides a large number of helpers for working with +assets+, +dates+, +forms+,
3
+ # +numbers+ and model objects, to name a few. These helpers are available to all templates
4
+ # by default.
5
+ #
6
+ # In addition to using the standard template helpers provided in the Rails framework, creating custom helpers to
7
+ # extract complicated logic or reusable functionality is strongly encouraged. By default, the controller will
8
+ # include a helper whose name matches that of the controller, e.g., <tt>MyController</tt> will automatically
9
+ # include <tt>MyHelper</tt>.
10
+ #
11
+ # Additional helpers can be specified using the +helper+ class method in <tt>ActionController::Base</tt> or any
12
+ # controller which inherits from it.
13
+ #
14
+ # ==== Examples
15
+ # The +to_s+ method from the Time class can be wrapped in a helper method to display a custom message if
16
+ # the Time object is blank:
17
+ #
18
+ # module FormattedTimeHelper
19
+ # def format_time(time, format=:long, blank_message="&nbsp;")
20
+ # time.blank? ? blank_message : time.to_s(format)
21
+ # end
22
+ # end
23
+ #
24
+ # FormattedTimeHelper can now be included in a controller, using the +helper+ class method:
25
+ #
26
+ # class EventsController < ActionController::Base
27
+ # helper FormattedTimeHelper
28
+ # def index
29
+ # @events = Event.find(:all)
30
+ # end
31
+ # end
32
+ #
33
+ # Then, in any view rendered by <tt>EventController</tt>, the <tt>format_time</tt> method can be called:
34
+ #
35
+ # <% @events.each do |event| -%>
36
+ # <p>
37
+ # <% format_time(event.time, :short, "N/A") %> | <%= event.name %>
38
+ # </p>
39
+ # <% end -%>
40
+ #
41
+ # Finally, assuming we have two event instances, one which has a time and one which does not,
42
+ # the output might look like this:
43
+ #
44
+ # 23 Aug 11:30 | Carolina Railhawks Soccer Match
45
+ # N/A | Carolina Railhaws Training Workshop
46
+ #
47
+ module Helpers
48
+ extend ActiveSupport::Concern
49
+
50
+ include AbstractController::Helpers
51
+
52
+ included do
53
+ # Set the default directory for helpers
54
+ extlib_inheritable_accessor(:helpers_dir) do
55
+ defined?(Rails) ? "#{Rails.root}/app/helpers" : "app/helpers"
56
+ end
57
+ end
58
+
59
+ module ClassMethods
60
+ def inherited(klass)
61
+ klass.class_eval { default_helper_module! unless name.blank? }
62
+ super
63
+ end
64
+
65
+ # Declares helper accessors for controller attributes. For example, the
66
+ # following adds new +name+ and <tt>name=</tt> instance methods to a
67
+ # controller and makes them available to the view:
68
+ # helper_attr :name
69
+ # attr_accessor :name
70
+ #
71
+ # ==== Parameters
72
+ # *attrs<Array[String, Symbol]>:: Names of attributes to be converted
73
+ # into helpers.
74
+ def helper_attr(*attrs)
75
+ attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
76
+ end
77
+
78
+ # Provides a proxy to access helpers methods from outside the view.
79
+ def helpers
80
+ @helper_proxy ||= ActionView::Base.new.extend(_helpers)
81
+ end
82
+
83
+ private
84
+ # Overwrite _modules_for_helpers to accept :all as argument, which loads
85
+ # all helpers in helpers_dir.
86
+ #
87
+ # ==== Parameters
88
+ # args<Array[String, Symbol, Module, all]>:: A list of helpers
89
+ #
90
+ # ==== Returns
91
+ # Array[Module]:: A normalized list of modules for the list of
92
+ # helpers provided.
93
+ def _modules_for_helpers(args)
94
+ args += all_application_helpers if args.delete(:all)
95
+ super(args)
96
+ end
97
+
98
+ def default_helper_module!
99
+ module_name = name.sub(/Controller$/, '')
100
+ module_path = module_name.underscore
101
+ helper module_path
102
+ rescue MissingSourceFile => e
103
+ raise e unless e.is_missing? "#{module_path}_helper"
104
+ rescue NameError => e
105
+ raise e unless e.missing_name? "#{module_name}Helper"
106
+ end
107
+
108
+ # Extract helper names from files in app/helpers/**/*.rb
109
+ def all_application_helpers
110
+ extract = /^#{Regexp.quote(helpers_dir)}\/?(.*)_helper.rb$/
111
+ Dir["#{helpers_dir}/**/*_helper.rb"].map { |file| file.sub extract, '\1' }
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,47 @@
1
+ module ActionController
2
+ # ActionController::HideActions adds the ability to prevent public methods on a controller
3
+ # to be called as actions.
4
+ module HideActions
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ extlib_inheritable_accessor(:hidden_actions) { Set.new }
9
+ end
10
+
11
+ private
12
+
13
+ # Overrides AbstractController::Base#action_method? to return false if the
14
+ # action name is in the list of hidden actions.
15
+ def action_method?(action_name)
16
+ self.class.visible_action?(action_name) do
17
+ !hidden_actions.include?(action_name) && super
18
+ end
19
+ end
20
+
21
+ module ClassMethods
22
+ # Sets all of the actions passed in as hidden actions.
23
+ #
24
+ # ==== Parameters
25
+ # *args<#to_s>:: A list of actions
26
+ def hide_action(*args)
27
+ hidden_actions.merge(args.map! {|a| a.to_s })
28
+ end
29
+
30
+ def inherited(klass)
31
+ klass.instance_variable_set("@visible_actions", {})
32
+ super
33
+ end
34
+
35
+ def visible_action?(action_name)
36
+ return @visible_actions[action_name] if @visible_actions.key?(action_name)
37
+ @visible_actions[action_name] = yield
38
+ end
39
+
40
+ # Overrides AbstractController::Base#action_methods to remove any methods
41
+ # that are listed as hidden methods.
42
+ def action_methods
43
+ @action_methods ||= Set.new(super.reject {|name| hidden_actions.include?(name)})
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,312 @@
1
+ require 'active_support/base64'
2
+
3
+ module ActionController
4
+ module HttpAuthentication
5
+ # Makes it dead easy to do HTTP Basic authentication.
6
+ #
7
+ # Simple Basic example:
8
+ #
9
+ # class PostsController < ApplicationController
10
+ # USER_NAME, PASSWORD = "dhh", "secret"
11
+ #
12
+ # before_filter :authenticate, :except => [ :index ]
13
+ #
14
+ # def index
15
+ # render :text => "Everyone can see me!"
16
+ # end
17
+ #
18
+ # def edit
19
+ # render :text => "I'm only accessible if you know the password"
20
+ # end
21
+ #
22
+ # private
23
+ # def authenticate
24
+ # authenticate_or_request_with_http_basic do |user_name, password|
25
+ # user_name == USER_NAME && password == PASSWORD
26
+ # end
27
+ # end
28
+ # end
29
+ #
30
+ #
31
+ # Here is a more advanced Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
32
+ # the regular HTML interface is protected by a session approach:
33
+ #
34
+ # class ApplicationController < ActionController::Base
35
+ # before_filter :set_account, :authenticate
36
+ #
37
+ # protected
38
+ # def set_account
39
+ # @account = Account.find_by_url_name(request.subdomains.first)
40
+ # end
41
+ #
42
+ # def authenticate
43
+ # case request.format
44
+ # when Mime::XML, Mime::ATOM
45
+ # if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
46
+ # @current_user = user
47
+ # else
48
+ # request_http_basic_authentication
49
+ # end
50
+ # else
51
+ # if session_authenticated?
52
+ # @current_user = @account.users.find(session[:authenticated][:user_id])
53
+ # else
54
+ # redirect_to(login_url) and return false
55
+ # end
56
+ # end
57
+ # end
58
+ # end
59
+ #
60
+ # In your integration tests, you can do something like this:
61
+ #
62
+ # def test_access_granted_from_xml
63
+ # get(
64
+ # "/notes/1.xml", nil,
65
+ # :authorization => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
66
+ # )
67
+ #
68
+ # assert_equal 200, status
69
+ # end
70
+ #
71
+ # Simple Digest example:
72
+ #
73
+ # require 'digest/md5'
74
+ # class PostsController < ApplicationController
75
+ # REALM = "SuperSecret"
76
+ # USERS = {"dhh" => "secret", #plain text password
77
+ # "dap" => Digest:MD5::hexdigest(["dap",REALM,"secret"].join(":")) #ha1 digest password
78
+ #
79
+ # before_filter :authenticate, :except => [:index]
80
+ #
81
+ # def index
82
+ # render :text => "Everyone can see me!"
83
+ # end
84
+ #
85
+ # def edit
86
+ # render :text => "I'm only accessible if you know the password"
87
+ # end
88
+ #
89
+ # private
90
+ # def authenticate
91
+ # authenticate_or_request_with_http_digest(REALM) do |username|
92
+ # USERS[username]
93
+ # end
94
+ # end
95
+ # end
96
+ #
97
+ # NOTE: The +authenticate_or_request_with_http_digest+ block must return the user's password or the ha1 digest hash so the framework can appropriately
98
+ # hash to check the user's credentials. Returning +nil+ will cause authentication to fail.
99
+ # Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
100
+ # the password file or database is compromised, the attacker would be able to use the ha1 hash to
101
+ # authenticate as the user at this +realm+, but would not have the user's password to try using at
102
+ # other sites.
103
+ #
104
+ # On shared hosts, Apache sometimes doesn't pass authentication headers to
105
+ # FCGI instances. If your environment matches this description and you cannot
106
+ # authenticate, try this rule in your Apache setup:
107
+ #
108
+ # RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
109
+ module Basic
110
+ extend self
111
+
112
+ module ControllerMethods
113
+ def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
114
+ authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
115
+ end
116
+
117
+ def authenticate_with_http_basic(&login_procedure)
118
+ HttpAuthentication::Basic.authenticate(request, &login_procedure)
119
+ end
120
+
121
+ def request_http_basic_authentication(realm = "Application")
122
+ HttpAuthentication::Basic.authentication_request(self, realm)
123
+ end
124
+ end
125
+
126
+ def authenticate(request, &login_procedure)
127
+ unless authorization(request).blank?
128
+ login_procedure.call(*user_name_and_password(request))
129
+ end
130
+ end
131
+
132
+ def user_name_and_password(request)
133
+ decode_credentials(request).split(/:/, 2)
134
+ end
135
+
136
+ def authorization(request)
137
+ request.env['HTTP_AUTHORIZATION'] ||
138
+ request.env['X-HTTP_AUTHORIZATION'] ||
139
+ request.env['X_HTTP_AUTHORIZATION'] ||
140
+ request.env['REDIRECT_X_HTTP_AUTHORIZATION']
141
+ end
142
+
143
+ def decode_credentials(request)
144
+ ActiveSupport::Base64.decode64(authorization(request).split(' ', 2).last || '')
145
+ end
146
+
147
+ def encode_credentials(user_name, password)
148
+ "Basic #{ActiveSupport::Base64.encode64("#{user_name}:#{password}")}"
149
+ end
150
+
151
+ def authentication_request(controller, realm)
152
+ controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
153
+ controller.response_body = "HTTP Basic: Access denied.\n"
154
+ controller.status = 401
155
+ end
156
+ end
157
+
158
+ module Digest
159
+ extend self
160
+
161
+ module ControllerMethods
162
+ def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
163
+ authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
164
+ end
165
+
166
+ # Authenticate with HTTP Digest, returns true or false
167
+ def authenticate_with_http_digest(realm = "Application", &password_procedure)
168
+ HttpAuthentication::Digest.authenticate(request, realm, &password_procedure)
169
+ end
170
+
171
+ # Render output including the HTTP Digest authentication header
172
+ def request_http_digest_authentication(realm = "Application", message = nil)
173
+ HttpAuthentication::Digest.authentication_request(self, realm, message)
174
+ end
175
+ end
176
+
177
+ # Returns false on a valid response, true otherwise
178
+ def authenticate(request, realm, &password_procedure)
179
+ authorization(request) && validate_digest_response(request, realm, &password_procedure)
180
+ end
181
+
182
+ def authorization(request)
183
+ request.env['HTTP_AUTHORIZATION'] ||
184
+ request.env['X-HTTP_AUTHORIZATION'] ||
185
+ request.env['X_HTTP_AUTHORIZATION'] ||
186
+ request.env['REDIRECT_X_HTTP_AUTHORIZATION']
187
+ end
188
+
189
+ # Returns false unless the request credentials response value matches the expected value.
190
+ # First try the password as a ha1 digest password. If this fails, then try it as a plain
191
+ # text password.
192
+ def validate_digest_response(request, realm, &password_procedure)
193
+ credentials = decode_credentials_header(request)
194
+ valid_nonce = validate_nonce(request, credentials[:nonce])
195
+
196
+ if valid_nonce && realm == credentials[:realm] && opaque == credentials[:opaque]
197
+ password = password_procedure.call(credentials[:username])
198
+ return false unless password
199
+
200
+ method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
201
+ uri = credentials[:uri][0,1] == '/' ? request.request_uri : request.url
202
+
203
+ [true, false].any? do |password_is_ha1|
204
+ expected = expected_response(method, uri, credentials, password, password_is_ha1)
205
+ expected == credentials[:response]
206
+ end
207
+ end
208
+ end
209
+
210
+ # Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
211
+ # Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
212
+ # of a plain-text password.
213
+ def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
214
+ ha1 = password_is_ha1 ? password : ha1(credentials, password)
215
+ ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
216
+ ::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
217
+ end
218
+
219
+ def ha1(credentials, password)
220
+ ::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
221
+ end
222
+
223
+ def encode_credentials(http_method, credentials, password, password_is_ha1)
224
+ credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
225
+ "Digest " + credentials.sort_by {|x| x[0].to_s }.inject([]) {|a, v| a << "#{v[0]}='#{v[1]}'" }.join(', ')
226
+ end
227
+
228
+ def decode_credentials_header(request)
229
+ decode_credentials(authorization(request))
230
+ end
231
+
232
+ def decode_credentials(header)
233
+ header.to_s.gsub(/^Digest\s+/,'').split(',').inject({}) do |hash, pair|
234
+ key, value = pair.split('=', 2)
235
+ hash[key.strip.to_sym] = value.to_s.gsub(/^"|"$/,'').gsub(/'/, '')
236
+ hash
237
+ end
238
+ end
239
+
240
+ def authentication_header(controller, realm)
241
+ controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
242
+ end
243
+
244
+ def authentication_request(controller, realm, message = nil)
245
+ message ||= "HTTP Digest: Access denied.\n"
246
+ authentication_header(controller, realm)
247
+ controller.response_body = message
248
+ controller.status = 401
249
+ end
250
+
251
+ # Uses an MD5 digest based on time to generate a value to be used only once.
252
+ #
253
+ # A server-specified data string which should be uniquely generated each time a 401 response is made.
254
+ # It is recommended that this string be base64 or hexadecimal data.
255
+ # Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
256
+ #
257
+ # The contents of the nonce are implementation dependent.
258
+ # The quality of the implementation depends on a good choice.
259
+ # A nonce might, for example, be constructed as the base 64 encoding of
260
+ #
261
+ # => time-stamp H(time-stamp ":" ETag ":" private-key)
262
+ #
263
+ # where time-stamp is a server-generated time or other non-repeating value,
264
+ # ETag is the value of the HTTP ETag header associated with the requested entity,
265
+ # and private-key is data known only to the server.
266
+ # With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
267
+ # reject the request if it did not match the nonce from that header or
268
+ # if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
269
+ # The inclusion of the ETag prevents a replay request for an updated version of the resource.
270
+ # (Note: including the IP address of the client in the nonce would appear to offer the server the ability
271
+ # to limit the reuse of the nonce to the same client that originally got it.
272
+ # However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
273
+ # Also, IP address spoofing is not that hard.)
274
+ #
275
+ # An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
276
+ # protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
277
+ # POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
278
+ # of this document.
279
+ #
280
+ # The nonce is opaque to the client. Composed of Time, and hash of Time with secret
281
+ # key from the Rails session secret generated upon creation of project. Ensures
282
+ # the time cannot be modified by client.
283
+ def nonce(time = Time.now)
284
+ t = time.to_i
285
+ hashed = [t, secret_key]
286
+ digest = ::Digest::MD5.hexdigest(hashed.join(":"))
287
+ ActiveSupport::Base64.encode64("#{t}:#{digest}").gsub("\n", '')
288
+ end
289
+
290
+ # Might want a shorter timeout depending on whether the request
291
+ # is a PUT or POST, and if client is browser or web service.
292
+ # Can be much shorter if the Stale directive is implemented. This would
293
+ # allow a user to use new nonce without prompting user again for their
294
+ # username and password.
295
+ def validate_nonce(request, value, seconds_to_timeout=5*60)
296
+ t = ActiveSupport::Base64.decode64(value).split(":").first.to_i
297
+ nonce(t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
298
+ end
299
+
300
+ # Opaque based on random generation - but changing each request?
301
+ def opaque()
302
+ ::Digest::MD5.hexdigest(secret_key)
303
+ end
304
+
305
+ # Set in /initializers/session_store.rb, and loaded even if sessions are not in use.
306
+ def secret_key
307
+ ActionController::Base.session_options[:secret]
308
+ end
309
+
310
+ end
311
+ end
312
+ end