##// END OF EJS Templates
Makes the API accepts the X-Redmine-API-Key header to hold the API key....
Jean-Philippe Lang -
r4459:07fe46e9dfc1
parent child
Show More
@@ -1,473 +1,482
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require 'uri'
19 19 require 'cgi'
20 20
21 21 class ApplicationController < ActionController::Base
22 22 include Redmine::I18n
23 23
24 24 layout 'base'
25 25 exempt_from_layout 'builder', 'rsb'
26 26
27 27 # Remove broken cookie after upgrade from 0.8.x (#4292)
28 28 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
29 29 # TODO: remove it when Rails is fixed
30 30 before_filter :delete_broken_cookies
31 31 def delete_broken_cookies
32 32 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
33 33 cookies.delete '_redmine_session'
34 34 redirect_to home_path
35 35 return false
36 36 end
37 37 end
38 38
39 39 before_filter :user_setup, :check_if_login_required, :set_localization
40 40 filter_parameter_logging :password
41 41 protect_from_forgery
42 42
43 43 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
44 44
45 45 include Redmine::Search::Controller
46 46 include Redmine::MenuManager::MenuController
47 47 helper Redmine::MenuManager::MenuHelper
48 48
49 49 Redmine::Scm::Base.all.each do |scm|
50 50 require_dependency "repository/#{scm.underscore}"
51 51 end
52 52
53 53 def user_setup
54 54 # Check the settings cache for each request
55 55 Setting.check_cache
56 56 # Find the current user
57 57 User.current = find_current_user
58 58 end
59 59
60 60 # Returns the current user or nil if no user is logged in
61 61 # and starts a session if needed
62 62 def find_current_user
63 63 if session[:user_id]
64 64 # existing session
65 65 (User.active.find(session[:user_id]) rescue nil)
66 66 elsif cookies[:autologin] && Setting.autologin?
67 67 # auto-login feature starts a new session
68 68 user = User.try_to_autologin(cookies[:autologin])
69 69 session[:user_id] = user.id if user
70 70 user
71 71 elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action])
72 72 # RSS key authentication does not start a session
73 73 User.find_by_rss_key(params[:key])
74 elsif Setting.rest_api_enabled? && ['xml', 'json'].include?(params[:format])
75 if params[:key].present? && accept_key_auth_actions.include?(params[:action])
74 elsif Setting.rest_api_enabled? && api_request?
75 if (key = api_key_from_request) && accept_key_auth_actions.include?(params[:action])
76 76 # Use API key
77 User.find_by_api_key(params[:key])
77 User.find_by_api_key(key)
78 78 else
79 79 # HTTP Basic, either username/password or API key/random
80 80 authenticate_with_http_basic do |username, password|
81 81 User.try_to_login(username, password) || User.find_by_api_key(username)
82 82 end
83 83 end
84 84 end
85 85 end
86 86
87 87 # Sets the logged in user
88 88 def logged_user=(user)
89 89 reset_session
90 90 if user && user.is_a?(User)
91 91 User.current = user
92 92 session[:user_id] = user.id
93 93 else
94 94 User.current = User.anonymous
95 95 end
96 96 end
97 97
98 98 # check if login is globally required to access the application
99 99 def check_if_login_required
100 100 # no check needed if user is already logged in
101 101 return true if User.current.logged?
102 102 require_login if Setting.login_required?
103 103 end
104 104
105 105 def set_localization
106 106 lang = nil
107 107 if User.current.logged?
108 108 lang = find_language(User.current.language)
109 109 end
110 110 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
111 111 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
112 112 if !accept_lang.blank?
113 113 accept_lang = accept_lang.downcase
114 114 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
115 115 end
116 116 end
117 117 lang ||= Setting.default_language
118 118 set_language_if_valid(lang)
119 119 end
120 120
121 121 def require_login
122 122 if !User.current.logged?
123 123 # Extract only the basic url parameters on non-GET requests
124 124 if request.get?
125 125 url = url_for(params)
126 126 else
127 127 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
128 128 end
129 129 respond_to do |format|
130 130 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
131 131 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
132 132 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
133 133 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
134 134 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
135 135 end
136 136 return false
137 137 end
138 138 true
139 139 end
140 140
141 141 def require_admin
142 142 return unless require_login
143 143 if !User.current.admin?
144 144 render_403
145 145 return false
146 146 end
147 147 true
148 148 end
149 149
150 150 def deny_access
151 151 User.current.logged? ? render_403 : require_login
152 152 end
153 153
154 154 # Authorize the user for the requested action
155 155 def authorize(ctrl = params[:controller], action = params[:action], global = false)
156 156 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
157 157 if allowed
158 158 true
159 159 else
160 160 if @project && @project.archived?
161 161 render_403 :message => :notice_not_authorized_archived_project
162 162 else
163 163 deny_access
164 164 end
165 165 end
166 166 end
167 167
168 168 # Authorize the user for the requested action outside a project
169 169 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
170 170 authorize(ctrl, action, global)
171 171 end
172 172
173 173 # Find project of id params[:id]
174 174 def find_project
175 175 @project = Project.find(params[:id])
176 176 rescue ActiveRecord::RecordNotFound
177 177 render_404
178 178 end
179 179
180 180 # Find project of id params[:project_id]
181 181 def find_project_by_project_id
182 182 @project = Project.find(params[:project_id])
183 183 rescue ActiveRecord::RecordNotFound
184 184 render_404
185 185 end
186 186
187 187 # Find a project based on params[:project_id]
188 188 # TODO: some subclasses override this, see about merging their logic
189 189 def find_optional_project
190 190 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
191 191 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
192 192 allowed ? true : deny_access
193 193 rescue ActiveRecord::RecordNotFound
194 194 render_404
195 195 end
196 196
197 197 # Finds and sets @project based on @object.project
198 198 def find_project_from_association
199 199 render_404 unless @object.present?
200 200
201 201 @project = @object.project
202 202 rescue ActiveRecord::RecordNotFound
203 203 render_404
204 204 end
205 205
206 206 def find_model_object
207 207 model = self.class.read_inheritable_attribute('model_object')
208 208 if model
209 209 @object = model.find(params[:id])
210 210 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
211 211 end
212 212 rescue ActiveRecord::RecordNotFound
213 213 render_404
214 214 end
215 215
216 216 def self.model_object(model)
217 217 write_inheritable_attribute('model_object', model)
218 218 end
219 219
220 220 # Filter for bulk issue operations
221 221 def find_issues
222 222 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
223 223 raise ActiveRecord::RecordNotFound if @issues.empty?
224 224 @projects = @issues.collect(&:project).compact.uniq
225 225 @project = @projects.first if @projects.size == 1
226 226 rescue ActiveRecord::RecordNotFound
227 227 render_404
228 228 end
229 229
230 230 # Check if project is unique before bulk operations
231 231 def check_project_uniqueness
232 232 unless @project
233 233 # TODO: let users bulk edit/move/destroy issues from different projects
234 234 render_error 'Can not bulk edit/move/destroy issues from different projects'
235 235 return false
236 236 end
237 237 end
238 238
239 239 # make sure that the user is a member of the project (or admin) if project is private
240 240 # used as a before_filter for actions that do not require any particular permission on the project
241 241 def check_project_privacy
242 242 if @project && @project.active?
243 243 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
244 244 true
245 245 else
246 246 User.current.logged? ? render_403 : require_login
247 247 end
248 248 else
249 249 @project = nil
250 250 render_404
251 251 false
252 252 end
253 253 end
254 254
255 255 def back_url
256 256 params[:back_url] || request.env['HTTP_REFERER']
257 257 end
258 258
259 259 def redirect_back_or_default(default)
260 260 back_url = CGI.unescape(params[:back_url].to_s)
261 261 if !back_url.blank?
262 262 begin
263 263 uri = URI.parse(back_url)
264 264 # do not redirect user to another host or to the login or register page
265 265 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
266 266 redirect_to(back_url)
267 267 return
268 268 end
269 269 rescue URI::InvalidURIError
270 270 # redirect to default
271 271 end
272 272 end
273 273 redirect_to default
274 274 end
275 275
276 276 def render_403(options={})
277 277 @project = nil
278 278 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
279 279 return false
280 280 end
281 281
282 282 def render_404(options={})
283 283 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
284 284 return false
285 285 end
286 286
287 287 # Renders an error response
288 288 def render_error(arg)
289 289 arg = {:message => arg} unless arg.is_a?(Hash)
290 290
291 291 @message = arg[:message]
292 292 @message = l(@message) if @message.is_a?(Symbol)
293 293 @status = arg[:status] || 500
294 294
295 295 respond_to do |format|
296 296 format.html {
297 297 render :template => 'common/error', :layout => use_layout, :status => @status
298 298 }
299 299 format.atom { head @status }
300 300 format.xml { head @status }
301 301 format.js { head @status }
302 302 format.json { head @status }
303 303 end
304 304 end
305 305
306 306 # Picks which layout to use based on the request
307 307 #
308 308 # @return [boolean, string] name of the layout to use or false for no layout
309 309 def use_layout
310 310 request.xhr? ? false : 'base'
311 311 end
312 312
313 313 def invalid_authenticity_token
314 314 if api_request?
315 315 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
316 316 end
317 317 render_error "Invalid form authenticity token."
318 318 end
319 319
320 320 def render_feed(items, options={})
321 321 @items = items || []
322 322 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
323 323 @items = @items.slice(0, Setting.feeds_limit.to_i)
324 324 @title = options[:title] || Setting.app_title
325 325 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
326 326 end
327 327
328 328 def self.accept_key_auth(*actions)
329 329 actions = actions.flatten.map(&:to_s)
330 330 write_inheritable_attribute('accept_key_auth_actions', actions)
331 331 end
332 332
333 333 def accept_key_auth_actions
334 334 self.class.read_inheritable_attribute('accept_key_auth_actions') || []
335 335 end
336 336
337 337 # Returns the number of objects that should be displayed
338 338 # on the paginated list
339 339 def per_page_option
340 340 per_page = nil
341 341 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
342 342 per_page = params[:per_page].to_s.to_i
343 343 session[:per_page] = per_page
344 344 elsif session[:per_page]
345 345 per_page = session[:per_page]
346 346 else
347 347 per_page = Setting.per_page_options_array.first || 25
348 348 end
349 349 per_page
350 350 end
351 351
352 352 # Returns offset and limit used to retrieve objects
353 353 # for an API response based on offset, limit and page parameters
354 354 def api_offset_and_limit(options=params)
355 355 if options[:offset].present?
356 356 offset = options[:offset].to_i
357 357 if offset < 0
358 358 offset = 0
359 359 end
360 360 end
361 361 limit = options[:limit].to_i
362 362 if limit < 1
363 363 limit = 25
364 364 elsif limit > 100
365 365 limit = 100
366 366 end
367 367 if offset.nil? && options[:page].present?
368 368 offset = (options[:page].to_i - 1) * limit
369 369 offset = 0 if offset < 0
370 370 end
371 371 offset ||= 0
372 372
373 373 [offset, limit]
374 374 end
375 375
376 376 # qvalues http header parser
377 377 # code taken from webrick
378 378 def parse_qvalues(value)
379 379 tmp = []
380 380 if value
381 381 parts = value.split(/,\s*/)
382 382 parts.each {|part|
383 383 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
384 384 val = m[1]
385 385 q = (m[2] or 1).to_f
386 386 tmp.push([val, q])
387 387 end
388 388 }
389 389 tmp = tmp.sort_by{|val, q| -q}
390 390 tmp.collect!{|val, q| val}
391 391 end
392 392 return tmp
393 393 rescue
394 394 nil
395 395 end
396 396
397 397 # Returns a string that can be used as filename value in Content-Disposition header
398 398 def filename_for_content_disposition(name)
399 399 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
400 400 end
401 401
402 402 def api_request?
403 403 %w(xml json).include? params[:format]
404 404 end
405
406 # Returns the API key present in the request
407 def api_key_from_request
408 if params[:key].present?
409 params[:key]
410 elsif request.headers["X-Redmine-API-Key"].present?
411 request.headers["X-Redmine-API-Key"]
412 end
413 end
405 414
406 415 # Renders a warning flash if obj has unsaved attachments
407 416 def render_attachment_warning_if_needed(obj)
408 417 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
409 418 end
410 419
411 420 # Sets the `flash` notice or error based the number of issues that did not save
412 421 #
413 422 # @param [Array, Issue] issues all of the saved and unsaved Issues
414 423 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
415 424 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
416 425 if unsaved_issue_ids.empty?
417 426 flash[:notice] = l(:notice_successful_update) unless issues.empty?
418 427 else
419 428 flash[:error] = l(:notice_failed_to_save_issues,
420 429 :count => unsaved_issue_ids.size,
421 430 :total => issues.size,
422 431 :ids => '#' + unsaved_issue_ids.join(', #'))
423 432 end
424 433 end
425 434
426 435 # Rescues an invalid query statement. Just in case...
427 436 def query_statement_invalid(exception)
428 437 logger.error "Query::StatementInvalid: #{exception.message}" if logger
429 438 session.delete(:query)
430 439 sort_clear if respond_to?(:sort_clear)
431 440 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
432 441 end
433 442
434 443 # Converts the errors on an ActiveRecord object into a common JSON format
435 444 def object_errors_to_json(object)
436 445 object.errors.collect do |attribute, error|
437 446 { attribute => error }
438 447 end.to_json
439 448 end
440 449
441 450 # Renders API response on validation failure
442 451 def render_validation_errors(object)
443 452 options = { :status => :unprocessable_entity, :layout => false }
444 453 options.merge!(case params[:format]
445 454 when 'xml'; { :xml => object.errors }
446 455 when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance
447 456 else
448 457 raise "Unknown format #{params[:format]} in #render_validation_errors"
449 458 end
450 459 )
451 460 render options
452 461 end
453 462
454 463 # Overrides #default_template so that the api template
455 464 # is used automatically if it exists
456 465 def default_template(action_name = self.action_name)
457 466 if api_request?
458 467 begin
459 468 return self.view_paths.find_template(default_template_name(action_name), 'api')
460 469 rescue ::ActionView::MissingTemplate
461 470 # the api template was not found
462 471 # fallback to the default behaviour
463 472 end
464 473 end
465 474 super
466 475 end
467 476
468 477 # Overrides #pick_layout so that #render with no arguments
469 478 # doesn't use the layout for api requests
470 479 def pick_layout(*args)
471 480 api_request? ? nil : super
472 481 end
473 482 end
@@ -1,420 +1,434
1 1 # redMine - project management software
2 2 # Copyright (C) 2006 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 ENV["RAILS_ENV"] = "test"
19 19 require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
20 20 require 'test_help'
21 21 require File.expand_path(File.dirname(__FILE__) + '/helper_testcase')
22 22 require File.join(RAILS_ROOT,'test', 'mocks', 'open_id_authentication_mock.rb')
23 23
24 24 require File.expand_path(File.dirname(__FILE__) + '/object_daddy_helpers')
25 25 include ObjectDaddyHelpers
26 26
27 27 class ActiveSupport::TestCase
28 28 # Transactional fixtures accelerate your tests by wrapping each test method
29 29 # in a transaction that's rolled back on completion. This ensures that the
30 30 # test database remains unchanged so your fixtures don't have to be reloaded
31 31 # between every test method. Fewer database queries means faster tests.
32 32 #
33 33 # Read Mike Clark's excellent walkthrough at
34 34 # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
35 35 #
36 36 # Every Active Record database supports transactions except MyISAM tables
37 37 # in MySQL. Turn off transactional fixtures in this case; however, if you
38 38 # don't care one way or the other, switching from MyISAM to InnoDB tables
39 39 # is recommended.
40 40 self.use_transactional_fixtures = true
41 41
42 42 # Instantiated fixtures are slow, but give you @david where otherwise you
43 43 # would need people(:david). If you don't want to migrate your existing
44 44 # test cases which use the @david style and don't mind the speed hit (each
45 45 # instantiated fixtures translates to a database query per test method),
46 46 # then set this back to true.
47 47 self.use_instantiated_fixtures = false
48 48
49 49 # Add more helper methods to be used by all tests here...
50 50
51 51 def log_user(login, password)
52 52 User.anonymous
53 53 get "/login"
54 54 assert_equal nil, session[:user_id]
55 55 assert_response :success
56 56 assert_template "account/login"
57 57 post "/login", :username => login, :password => password
58 58 assert_equal login, User.find(session[:user_id]).login
59 59 end
60 60
61 61 def uploaded_test_file(name, mime)
62 62 ActionController::TestUploadedFile.new(ActiveSupport::TestCase.fixture_path + "/files/#{name}", mime)
63 63 end
64 64
65 65 # Mock out a file
66 66 def self.mock_file
67 67 file = 'a_file.png'
68 68 file.stubs(:size).returns(32)
69 69 file.stubs(:original_filename).returns('a_file.png')
70 70 file.stubs(:content_type).returns('image/png')
71 71 file.stubs(:read).returns(false)
72 72 file
73 73 end
74 74
75 75 def mock_file
76 76 self.class.mock_file
77 77 end
78 78
79 79 # Use a temporary directory for attachment related tests
80 80 def set_tmp_attachments_directory
81 81 Dir.mkdir "#{RAILS_ROOT}/tmp/test" unless File.directory?("#{RAILS_ROOT}/tmp/test")
82 82 Dir.mkdir "#{RAILS_ROOT}/tmp/test/attachments" unless File.directory?("#{RAILS_ROOT}/tmp/test/attachments")
83 83 Attachment.storage_path = "#{RAILS_ROOT}/tmp/test/attachments"
84 84 end
85 85
86 86 def with_settings(options, &block)
87 87 saved_settings = options.keys.inject({}) {|h, k| h[k] = Setting[k].dup; h}
88 88 options.each {|k, v| Setting[k] = v}
89 89 yield
90 90 saved_settings.each {|k, v| Setting[k] = v}
91 91 end
92 92
93 93 def change_user_password(login, new_password)
94 94 user = User.first(:conditions => {:login => login})
95 95 user.password, user.password_confirmation = new_password, new_password
96 96 user.save!
97 97 end
98 98
99 99 def self.ldap_configured?
100 100 @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389)
101 101 return @test_ldap.bind
102 102 rescue Exception => e
103 103 # LDAP is not listening
104 104 return nil
105 105 end
106 106
107 107 # Returns the path to the test +vendor+ repository
108 108 def self.repository_path(vendor)
109 109 File.join(RAILS_ROOT.gsub(%r{config\/\.\.}, ''), "/tmp/test/#{vendor.downcase}_repository")
110 110 end
111 111
112 112 # Returns true if the +vendor+ test repository is configured
113 113 def self.repository_configured?(vendor)
114 114 File.directory?(repository_path(vendor))
115 115 end
116 116
117 117 def assert_error_tag(options={})
118 118 assert_tag({:attributes => { :id => 'errorExplanation' }}.merge(options))
119 119 end
120 120
121 121 # Shoulda macros
122 122 def self.should_render_404
123 123 should_respond_with :not_found
124 124 should_render_template 'common/error'
125 125 end
126 126
127 127 def self.should_have_before_filter(expected_method, options = {})
128 128 should_have_filter('before', expected_method, options)
129 129 end
130 130
131 131 def self.should_have_after_filter(expected_method, options = {})
132 132 should_have_filter('after', expected_method, options)
133 133 end
134 134
135 135 def self.should_have_filter(filter_type, expected_method, options)
136 136 description = "have #{filter_type}_filter :#{expected_method}"
137 137 description << " with #{options.inspect}" unless options.empty?
138 138
139 139 should description do
140 140 klass = "action_controller/filters/#{filter_type}_filter".classify.constantize
141 141 expected = klass.new(:filter, expected_method.to_sym, options)
142 142 assert_equal 1, @controller.class.filter_chain.select { |filter|
143 143 filter.method == expected.method && filter.kind == expected.kind &&
144 144 filter.options == expected.options && filter.class == expected.class
145 145 }.size
146 146 end
147 147 end
148 148
149 149 def self.should_show_the_old_and_new_values_for(prop_key, model, &block)
150 150 context "" do
151 151 setup do
152 152 if block_given?
153 153 instance_eval &block
154 154 else
155 155 @old_value = model.generate!
156 156 @new_value = model.generate!
157 157 end
158 158 end
159 159
160 160 should "use the new value's name" do
161 161 @detail = JournalDetail.generate!(:property => 'attr',
162 162 :old_value => @old_value.id,
163 163 :value => @new_value.id,
164 164 :prop_key => prop_key)
165 165
166 166 assert_match @new_value.name, show_detail(@detail, true)
167 167 end
168 168
169 169 should "use the old value's name" do
170 170 @detail = JournalDetail.generate!(:property => 'attr',
171 171 :old_value => @old_value.id,
172 172 :value => @new_value.id,
173 173 :prop_key => prop_key)
174 174
175 175 assert_match @old_value.name, show_detail(@detail, true)
176 176 end
177 177 end
178 178 end
179 179
180 180 def self.should_create_a_new_user(&block)
181 181 should "create a new user" do
182 182 user = instance_eval &block
183 183 assert user
184 184 assert_kind_of User, user
185 185 assert !user.new_record?
186 186 end
187 187 end
188 188
189 189 # Test that a request allows the three types of API authentication
190 190 #
191 191 # * HTTP Basic with username and password
192 192 # * HTTP Basic with an api key for the username
193 193 # * Key based with the key=X parameter
194 194 #
195 195 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
196 196 # @param [String] url the request url
197 197 # @param [optional, Hash] parameters additional request parameters
198 198 # @param [optional, Hash] options additional options
199 199 # @option options [Symbol] :success_code Successful response code (:success)
200 200 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
201 201 def self.should_allow_api_authentication(http_method, url, parameters={}, options={})
202 202 should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options)
203 203 should_allow_http_basic_auth_with_key(http_method, url, parameters, options)
204 204 should_allow_key_based_auth(http_method, url, parameters, options)
205 205 end
206 206
207 207 # Test that a request allows the username and password for HTTP BASIC
208 208 #
209 209 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
210 210 # @param [String] url the request url
211 211 # @param [optional, Hash] parameters additional request parameters
212 212 # @param [optional, Hash] options additional options
213 213 # @option options [Symbol] :success_code Successful response code (:success)
214 214 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
215 215 def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={})
216 216 success_code = options[:success_code] || :success
217 217 failure_code = options[:failure_code] || :unauthorized
218 218
219 219 context "should allow http basic auth using a username and password for #{http_method} #{url}" do
220 220 context "with a valid HTTP authentication" do
221 221 setup do
222 222 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password', :admin => true) # Admin so they can access the project
223 223 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
224 224 send(http_method, url, parameters, {:authorization => @authorization})
225 225 end
226 226
227 227 should_respond_with success_code
228 228 should_respond_with_content_type_based_on_url(url)
229 229 should "login as the user" do
230 230 assert_equal @user, User.current
231 231 end
232 232 end
233 233
234 234 context "with an invalid HTTP authentication" do
235 235 setup do
236 236 @user = User.generate_with_protected!
237 237 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
238 238 send(http_method, url, parameters, {:authorization => @authorization})
239 239 end
240 240
241 241 should_respond_with failure_code
242 242 should_respond_with_content_type_based_on_url(url)
243 243 should "not login as the user" do
244 244 assert_equal User.anonymous, User.current
245 245 end
246 246 end
247 247
248 248 context "without credentials" do
249 249 setup do
250 250 send(http_method, url, parameters, {:authorization => ''})
251 251 end
252 252
253 253 should_respond_with failure_code
254 254 should_respond_with_content_type_based_on_url(url)
255 255 should "include_www_authenticate_header" do
256 256 assert @controller.response.headers.has_key?('WWW-Authenticate')
257 257 end
258 258 end
259 259 end
260 260
261 261 end
262 262
263 263 # Test that a request allows the API key with HTTP BASIC
264 264 #
265 265 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
266 266 # @param [String] url the request url
267 267 # @param [optional, Hash] parameters additional request parameters
268 268 # @param [optional, Hash] options additional options
269 269 # @option options [Symbol] :success_code Successful response code (:success)
270 270 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
271 271 def self.should_allow_http_basic_auth_with_key(http_method, url, parameters={}, options={})
272 272 success_code = options[:success_code] || :success
273 273 failure_code = options[:failure_code] || :unauthorized
274 274
275 275 context "should allow http basic auth with a key for #{http_method} #{url}" do
276 276 context "with a valid HTTP authentication using the API token" do
277 277 setup do
278 278 @user = User.generate_with_protected!(:admin => true)
279 279 @token = Token.generate!(:user => @user, :action => 'api')
280 280 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
281 281 send(http_method, url, parameters, {:authorization => @authorization})
282 282 end
283 283
284 284 should_respond_with success_code
285 285 should_respond_with_content_type_based_on_url(url)
286 286 should_be_a_valid_response_string_based_on_url(url)
287 287 should "login as the user" do
288 288 assert_equal @user, User.current
289 289 end
290 290 end
291 291
292 292 context "with an invalid HTTP authentication" do
293 293 setup do
294 294 @user = User.generate_with_protected!
295 295 @token = Token.generate!(:user => @user, :action => 'feeds')
296 296 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
297 297 send(http_method, url, parameters, {:authorization => @authorization})
298 298 end
299 299
300 300 should_respond_with failure_code
301 301 should_respond_with_content_type_based_on_url(url)
302 302 should "not login as the user" do
303 303 assert_equal User.anonymous, User.current
304 304 end
305 305 end
306 306 end
307 307 end
308 308
309 309 # Test that a request allows full key authentication
310 310 #
311 311 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
312 312 # @param [String] url the request url, without the key=ZXY parameter
313 313 # @param [optional, Hash] parameters additional request parameters
314 314 # @param [optional, Hash] options additional options
315 315 # @option options [Symbol] :success_code Successful response code (:success)
316 316 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
317 317 def self.should_allow_key_based_auth(http_method, url, parameters={}, options={})
318 318 success_code = options[:success_code] || :success
319 319 failure_code = options[:failure_code] || :unauthorized
320 320
321 321 context "should allow key based auth using key=X for #{http_method} #{url}" do
322 322 context "with a valid api token" do
323 323 setup do
324 324 @user = User.generate_with_protected!(:admin => true)
325 325 @token = Token.generate!(:user => @user, :action => 'api')
326 326 # Simple url parse to add on ?key= or &key=
327 327 request_url = if url.match(/\?/)
328 328 url + "&key=#{@token.value}"
329 329 else
330 330 url + "?key=#{@token.value}"
331 331 end
332 332 send(http_method, request_url, parameters)
333 333 end
334 334
335 335 should_respond_with success_code
336 336 should_respond_with_content_type_based_on_url(url)
337 337 should_be_a_valid_response_string_based_on_url(url)
338 338 should "login as the user" do
339 339 assert_equal @user, User.current
340 340 end
341 341 end
342 342
343 343 context "with an invalid api token" do
344 344 setup do
345 345 @user = User.generate_with_protected!
346 346 @token = Token.generate!(:user => @user, :action => 'feeds')
347 347 # Simple url parse to add on ?key= or &key=
348 348 request_url = if url.match(/\?/)
349 349 url + "&key=#{@token.value}"
350 350 else
351 351 url + "?key=#{@token.value}"
352 352 end
353 353 send(http_method, request_url, parameters)
354 354 end
355 355
356 356 should_respond_with failure_code
357 357 should_respond_with_content_type_based_on_url(url)
358 358 should "not login as the user" do
359 359 assert_equal User.anonymous, User.current
360 360 end
361 361 end
362 362 end
363 363
364 context "should allow key based auth using X-Redmine-API-Key header for #{http_method} #{url}" do
365 setup do
366 @user = User.generate_with_protected!(:admin => true)
367 @token = Token.generate!(:user => @user, :action => 'api')
368 send(http_method, url, parameters, {'X-Redmine-API-Key' => @token.value.to_s})
369 end
370
371 should_respond_with success_code
372 should_respond_with_content_type_based_on_url(url)
373 should_be_a_valid_response_string_based_on_url(url)
374 should "login as the user" do
375 assert_equal @user, User.current
376 end
377 end
364 378 end
365 379
366 380 # Uses should_respond_with_content_type based on what's in the url:
367 381 #
368 382 # '/project/issues.xml' => should_respond_with_content_type :xml
369 383 # '/project/issues.json' => should_respond_with_content_type :json
370 384 #
371 385 # @param [String] url Request
372 386 def self.should_respond_with_content_type_based_on_url(url)
373 387 case
374 388 when url.match(/xml/i)
375 389 should_respond_with_content_type :xml
376 390 when url.match(/json/i)
377 391 should_respond_with_content_type :json
378 392 else
379 393 raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}"
380 394 end
381 395
382 396 end
383 397
384 398 # Uses the url to assert which format the response should be in
385 399 #
386 400 # '/project/issues.xml' => should_be_a_valid_xml_string
387 401 # '/project/issues.json' => should_be_a_valid_json_string
388 402 #
389 403 # @param [String] url Request
390 404 def self.should_be_a_valid_response_string_based_on_url(url)
391 405 case
392 406 when url.match(/xml/i)
393 407 should_be_a_valid_xml_string
394 408 when url.match(/json/i)
395 409 should_be_a_valid_json_string
396 410 else
397 411 raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}"
398 412 end
399 413
400 414 end
401 415
402 416 # Checks that the response is a valid JSON string
403 417 def self.should_be_a_valid_json_string
404 418 should "be a valid JSON string (or empty)" do
405 419 assert (response.body.blank? || ActiveSupport::JSON.decode(response.body))
406 420 end
407 421 end
408 422
409 423 # Checks that the response is a valid XML string
410 424 def self.should_be_a_valid_xml_string
411 425 should "be a valid XML string" do
412 426 assert REXML::Document.new(response.body)
413 427 end
414 428 end
415 429
416 430 end
417 431
418 432 # Simple module to "namespace" all of the API tests
419 433 module ApiTest
420 434 end
General Comments 0
You need to be logged in to leave comments. Login now