##// END OF EJS Templates
Adds an optional X-Redmine-Switch-User header to let admin users swicth user in API calls (#11755)....
Jean-Philippe Lang -
r10397:5344a35f723b
parent child
Show More
@@ -1,560 +1,575
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2012 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 Unauthorized < Exception; end
22 22
23 23 class ApplicationController < ActionController::Base
24 24 include Redmine::I18n
25 25
26 26 class_attribute :accept_api_auth_actions
27 27 class_attribute :accept_rss_auth_actions
28 28 class_attribute :model_object
29 29
30 30 layout 'base'
31 31
32 32 protect_from_forgery
33 33 def handle_unverified_request
34 34 super
35 35 cookies.delete(:autologin)
36 36 end
37 37
38 38 before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
39 39
40 40 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
41 41 rescue_from ::Unauthorized, :with => :deny_access
42 42 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
43 43
44 44 include Redmine::Search::Controller
45 45 include Redmine::MenuManager::MenuController
46 46 helper Redmine::MenuManager::MenuHelper
47 47
48 48 def session_expiration
49 49 if session[:user_id]
50 50 if session_expired? && !try_to_autologin
51 51 reset_session
52 52 flash[:error] = l(:error_session_expired)
53 53 redirect_to signin_url
54 54 else
55 55 session[:atime] = Time.now.utc.to_i
56 56 end
57 57 end
58 58 end
59 59
60 60 def session_expired?
61 61 if Setting.session_lifetime?
62 62 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
63 63 return true
64 64 end
65 65 end
66 66 if Setting.session_timeout?
67 67 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
68 68 return true
69 69 end
70 70 end
71 71 false
72 72 end
73 73
74 74 def start_user_session(user)
75 75 session[:user_id] = user.id
76 76 session[:ctime] = Time.now.utc.to_i
77 77 session[:atime] = Time.now.utc.to_i
78 78 end
79 79
80 80 def user_setup
81 81 # Check the settings cache for each request
82 82 Setting.check_cache
83 83 # Find the current user
84 84 User.current = find_current_user
85 85 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
86 86 end
87 87
88 88 # Returns the current user or nil if no user is logged in
89 89 # and starts a session if needed
90 90 def find_current_user
91 91 user = nil
92 92 unless api_request?
93 93 if session[:user_id]
94 94 # existing session
95 95 user = (User.active.find(session[:user_id]) rescue nil)
96 96 elsif autologin_user = try_to_autologin
97 97 user = autologin_user
98 98 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
99 99 # RSS key authentication does not start a session
100 100 user = User.find_by_rss_key(params[:key])
101 101 end
102 102 end
103 103 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
104 104 if (key = api_key_from_request)
105 105 # Use API key
106 106 user = User.find_by_api_key(key)
107 107 else
108 108 # HTTP Basic, either username/password or API key/random
109 109 authenticate_with_http_basic do |username, password|
110 110 user = User.try_to_login(username, password) || User.find_by_api_key(username)
111 111 end
112 112 end
113 # Switch user if requested by an admin user
114 if user && user.admin? && (username = api_switch_user_from_request)
115 su = User.find_by_login(username)
116 if su && su.active?
117 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
118 user = su
119 else
120 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
121 end
122 end
113 123 end
114 124 user
115 125 end
116 126
117 127 def try_to_autologin
118 128 if cookies[:autologin] && Setting.autologin?
119 129 # auto-login feature starts a new session
120 130 user = User.try_to_autologin(cookies[:autologin])
121 131 if user
122 132 reset_session
123 133 start_user_session(user)
124 134 end
125 135 user
126 136 end
127 137 end
128 138
129 139 # Sets the logged in user
130 140 def logged_user=(user)
131 141 reset_session
132 142 if user && user.is_a?(User)
133 143 User.current = user
134 144 start_user_session(user)
135 145 else
136 146 User.current = User.anonymous
137 147 end
138 148 end
139 149
140 150 # Logs out current user
141 151 def logout_user
142 152 if User.current.logged?
143 153 cookies.delete :autologin
144 154 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
145 155 self.logged_user = nil
146 156 end
147 157 end
148 158
149 159 # check if login is globally required to access the application
150 160 def check_if_login_required
151 161 # no check needed if user is already logged in
152 162 return true if User.current.logged?
153 163 require_login if Setting.login_required?
154 164 end
155 165
156 166 def set_localization
157 167 lang = nil
158 168 if User.current.logged?
159 169 lang = find_language(User.current.language)
160 170 end
161 171 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
162 172 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
163 173 if !accept_lang.blank?
164 174 accept_lang = accept_lang.downcase
165 175 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
166 176 end
167 177 end
168 178 lang ||= Setting.default_language
169 179 set_language_if_valid(lang)
170 180 end
171 181
172 182 def require_login
173 183 if !User.current.logged?
174 184 # Extract only the basic url parameters on non-GET requests
175 185 if request.get?
176 186 url = url_for(params)
177 187 else
178 188 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
179 189 end
180 190 respond_to do |format|
181 191 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
182 192 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
183 193 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
184 194 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
185 195 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
186 196 end
187 197 return false
188 198 end
189 199 true
190 200 end
191 201
192 202 def require_admin
193 203 return unless require_login
194 204 if !User.current.admin?
195 205 render_403
196 206 return false
197 207 end
198 208 true
199 209 end
200 210
201 211 def deny_access
202 212 User.current.logged? ? render_403 : require_login
203 213 end
204 214
205 215 # Authorize the user for the requested action
206 216 def authorize(ctrl = params[:controller], action = params[:action], global = false)
207 217 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
208 218 if allowed
209 219 true
210 220 else
211 221 if @project && @project.archived?
212 222 render_403 :message => :notice_not_authorized_archived_project
213 223 else
214 224 deny_access
215 225 end
216 226 end
217 227 end
218 228
219 229 # Authorize the user for the requested action outside a project
220 230 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
221 231 authorize(ctrl, action, global)
222 232 end
223 233
224 234 # Find project of id params[:id]
225 235 def find_project
226 236 @project = Project.find(params[:id])
227 237 rescue ActiveRecord::RecordNotFound
228 238 render_404
229 239 end
230 240
231 241 # Find project of id params[:project_id]
232 242 def find_project_by_project_id
233 243 @project = Project.find(params[:project_id])
234 244 rescue ActiveRecord::RecordNotFound
235 245 render_404
236 246 end
237 247
238 248 # Find a project based on params[:project_id]
239 249 # TODO: some subclasses override this, see about merging their logic
240 250 def find_optional_project
241 251 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
242 252 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
243 253 allowed ? true : deny_access
244 254 rescue ActiveRecord::RecordNotFound
245 255 render_404
246 256 end
247 257
248 258 # Finds and sets @project based on @object.project
249 259 def find_project_from_association
250 260 render_404 unless @object.present?
251 261
252 262 @project = @object.project
253 263 end
254 264
255 265 def find_model_object
256 266 model = self.class.model_object
257 267 if model
258 268 @object = model.find(params[:id])
259 269 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
260 270 end
261 271 rescue ActiveRecord::RecordNotFound
262 272 render_404
263 273 end
264 274
265 275 def self.model_object(model)
266 276 self.model_object = model
267 277 end
268 278
269 279 # Filter for bulk issue operations
270 280 def find_issues
271 281 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
272 282 raise ActiveRecord::RecordNotFound if @issues.empty?
273 283 if @issues.detect {|issue| !issue.visible?}
274 284 deny_access
275 285 return
276 286 end
277 287 @projects = @issues.collect(&:project).compact.uniq
278 288 @project = @projects.first if @projects.size == 1
279 289 rescue ActiveRecord::RecordNotFound
280 290 render_404
281 291 end
282 292
283 293 # make sure that the user is a member of the project (or admin) if project is private
284 294 # used as a before_filter for actions that do not require any particular permission on the project
285 295 def check_project_privacy
286 296 if @project && !@project.archived?
287 297 if @project.visible?
288 298 true
289 299 else
290 300 deny_access
291 301 end
292 302 else
293 303 @project = nil
294 304 render_404
295 305 false
296 306 end
297 307 end
298 308
299 309 def back_url
300 310 url = params[:back_url]
301 311 if url.nil? && referer = request.env['HTTP_REFERER']
302 312 url = CGI.unescape(referer.to_s)
303 313 end
304 314 url
305 315 end
306 316
307 317 def redirect_back_or_default(default)
308 318 back_url = params[:back_url].to_s
309 319 if back_url.present?
310 320 begin
311 321 uri = URI.parse(back_url)
312 322 # do not redirect user to another host or to the login or register page
313 323 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
314 324 redirect_to(back_url)
315 325 return
316 326 end
317 327 rescue URI::InvalidURIError
318 328 logger.warn("Could not redirect to invalid URL #{back_url}")
319 329 # redirect to default
320 330 end
321 331 end
322 332 redirect_to default
323 333 false
324 334 end
325 335
326 336 # Redirects to the request referer if present, redirects to args or call block otherwise.
327 337 def redirect_to_referer_or(*args, &block)
328 338 redirect_to :back
329 339 rescue ::ActionController::RedirectBackError
330 340 if args.any?
331 341 redirect_to *args
332 342 elsif block_given?
333 343 block.call
334 344 else
335 345 raise "#redirect_to_referer_or takes arguments or a block"
336 346 end
337 347 end
338 348
339 349 def render_403(options={})
340 350 @project = nil
341 351 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
342 352 return false
343 353 end
344 354
345 355 def render_404(options={})
346 356 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
347 357 return false
348 358 end
349 359
350 360 # Renders an error response
351 361 def render_error(arg)
352 362 arg = {:message => arg} unless arg.is_a?(Hash)
353 363
354 364 @message = arg[:message]
355 365 @message = l(@message) if @message.is_a?(Symbol)
356 366 @status = arg[:status] || 500
357 367
358 368 respond_to do |format|
359 369 format.html {
360 370 render :template => 'common/error', :layout => use_layout, :status => @status
361 371 }
362 372 format.any { head @status }
363 373 end
364 374 end
365 375
366 376 # Handler for ActionView::MissingTemplate exception
367 377 def missing_template
368 378 logger.warn "Missing template, responding with 404"
369 379 @project = nil
370 380 render_404
371 381 end
372 382
373 383 # Filter for actions that provide an API response
374 384 # but have no HTML representation for non admin users
375 385 def require_admin_or_api_request
376 386 return true if api_request?
377 387 if User.current.admin?
378 388 true
379 389 elsif User.current.logged?
380 390 render_error(:status => 406)
381 391 else
382 392 deny_access
383 393 end
384 394 end
385 395
386 396 # Picks which layout to use based on the request
387 397 #
388 398 # @return [boolean, string] name of the layout to use or false for no layout
389 399 def use_layout
390 400 request.xhr? ? false : 'base'
391 401 end
392 402
393 403 def invalid_authenticity_token
394 404 if api_request?
395 405 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
396 406 end
397 407 render_error "Invalid form authenticity token."
398 408 end
399 409
400 410 def render_feed(items, options={})
401 411 @items = items || []
402 412 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
403 413 @items = @items.slice(0, Setting.feeds_limit.to_i)
404 414 @title = options[:title] || Setting.app_title
405 415 render :template => "common/feed", :formats => [:atom], :layout => false,
406 416 :content_type => 'application/atom+xml'
407 417 end
408 418
409 419 def self.accept_rss_auth(*actions)
410 420 if actions.any?
411 421 self.accept_rss_auth_actions = actions
412 422 else
413 423 self.accept_rss_auth_actions || []
414 424 end
415 425 end
416 426
417 427 def accept_rss_auth?(action=action_name)
418 428 self.class.accept_rss_auth.include?(action.to_sym)
419 429 end
420 430
421 431 def self.accept_api_auth(*actions)
422 432 if actions.any?
423 433 self.accept_api_auth_actions = actions
424 434 else
425 435 self.accept_api_auth_actions || []
426 436 end
427 437 end
428 438
429 439 def accept_api_auth?(action=action_name)
430 440 self.class.accept_api_auth.include?(action.to_sym)
431 441 end
432 442
433 443 # Returns the number of objects that should be displayed
434 444 # on the paginated list
435 445 def per_page_option
436 446 per_page = nil
437 447 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
438 448 per_page = params[:per_page].to_s.to_i
439 449 session[:per_page] = per_page
440 450 elsif session[:per_page]
441 451 per_page = session[:per_page]
442 452 else
443 453 per_page = Setting.per_page_options_array.first || 25
444 454 end
445 455 per_page
446 456 end
447 457
448 458 # Returns offset and limit used to retrieve objects
449 459 # for an API response based on offset, limit and page parameters
450 460 def api_offset_and_limit(options=params)
451 461 if options[:offset].present?
452 462 offset = options[:offset].to_i
453 463 if offset < 0
454 464 offset = 0
455 465 end
456 466 end
457 467 limit = options[:limit].to_i
458 468 if limit < 1
459 469 limit = 25
460 470 elsif limit > 100
461 471 limit = 100
462 472 end
463 473 if offset.nil? && options[:page].present?
464 474 offset = (options[:page].to_i - 1) * limit
465 475 offset = 0 if offset < 0
466 476 end
467 477 offset ||= 0
468 478
469 479 [offset, limit]
470 480 end
471 481
472 482 # qvalues http header parser
473 483 # code taken from webrick
474 484 def parse_qvalues(value)
475 485 tmp = []
476 486 if value
477 487 parts = value.split(/,\s*/)
478 488 parts.each {|part|
479 489 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
480 490 val = m[1]
481 491 q = (m[2] or 1).to_f
482 492 tmp.push([val, q])
483 493 end
484 494 }
485 495 tmp = tmp.sort_by{|val, q| -q}
486 496 tmp.collect!{|val, q| val}
487 497 end
488 498 return tmp
489 499 rescue
490 500 nil
491 501 end
492 502
493 503 # Returns a string that can be used as filename value in Content-Disposition header
494 504 def filename_for_content_disposition(name)
495 505 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
496 506 end
497 507
498 508 def api_request?
499 509 %w(xml json).include? params[:format]
500 510 end
501 511
502 512 # Returns the API key present in the request
503 513 def api_key_from_request
504 514 if params[:key].present?
505 515 params[:key].to_s
506 516 elsif request.headers["X-Redmine-API-Key"].present?
507 517 request.headers["X-Redmine-API-Key"].to_s
508 518 end
509 519 end
510 520
521 # Returns the API 'switch user' value if present
522 def api_switch_user_from_request
523 request.headers["X-Redmine-Switch-User"].to_s.presence
524 end
525
511 526 # Renders a warning flash if obj has unsaved attachments
512 527 def render_attachment_warning_if_needed(obj)
513 528 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
514 529 end
515 530
516 531 # Sets the `flash` notice or error based the number of issues that did not save
517 532 #
518 533 # @param [Array, Issue] issues all of the saved and unsaved Issues
519 534 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
520 535 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
521 536 if unsaved_issue_ids.empty?
522 537 flash[:notice] = l(:notice_successful_update) unless issues.empty?
523 538 else
524 539 flash[:error] = l(:notice_failed_to_save_issues,
525 540 :count => unsaved_issue_ids.size,
526 541 :total => issues.size,
527 542 :ids => '#' + unsaved_issue_ids.join(', #'))
528 543 end
529 544 end
530 545
531 546 # Rescues an invalid query statement. Just in case...
532 547 def query_statement_invalid(exception)
533 548 logger.error "Query::StatementInvalid: #{exception.message}" if logger
534 549 session.delete(:query)
535 550 sort_clear if respond_to?(:sort_clear)
536 551 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
537 552 end
538 553
539 554 # Renders a 200 response for successfull updates or deletions via the API
540 555 def render_api_ok
541 556 # head :ok would return a response body with one space
542 557 render :text => '', :status => :ok, :layout => nil
543 558 end
544 559
545 560 # Renders API response on validation failure
546 561 def render_validation_errors(objects)
547 562 if objects.is_a?(Array)
548 563 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
549 564 else
550 565 @error_messages = objects.errors.full_messages
551 566 end
552 567 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
553 568 end
554 569
555 570 # Overrides #_include_layout? so that #render with no arguments
556 571 # doesn't use the layout for api requests
557 572 def _include_layout?(*args)
558 573 api_request? ? false : super
559 574 end
560 575 end
@@ -1,32 +1,73
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2012 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 File.expand_path('../../../test_helper', __FILE__)
19 19
20 20 class ApiTest::AuthenticationTest < ActionController::IntegrationTest
21 21 fixtures :users
22 22
23 def setup
24 Setting.rest_api_enabled = '1'
25 end
26
27 def teardown
28 Setting.rest_api_enabled = '0'
29 end
30
23 31 def test_api_request_should_not_use_user_session
24 32 log_user('jsmith', 'jsmith')
25 33
26 34 get '/users/current'
27 35 assert_response :success
28 36
29 37 get '/users/current.json'
30 38 assert_response 401
31 39 end
40
41 def test_api_should_accept_switch_user_header_for_admin_user
42 user = User.find(1)
43 su = User.find(4)
44
45 get '/users/current', {}, {'X-Redmine-API-Key' => user.api_key, 'X-Redmine-Switch-User' => su.login}
46 assert_response :success
47 assert_equal su, assigns(:user)
48 assert_equal su, User.current
49 end
50
51 def test_api_should_respond_with_412_when_trying_to_switch_to_a_invalid_user
52 get '/users/current', {}, {'X-Redmine-API-Key' => User.find(1).api_key, 'X-Redmine-Switch-User' => 'foobar'}
53 assert_response 412
54 end
55
56 def test_api_should_respond_with_412_when_trying_to_switch_to_a_locked_user
57 user = User.find(5)
58 assert user.locked?
59
60 get '/users/current', {}, {'X-Redmine-API-Key' => User.find(1).api_key, 'X-Redmine-Switch-User' => user.login}
61 assert_response 412
62 end
63
64 def test_api_should_not_accept_switch_user_header_for_non_admin_user
65 user = User.find(2)
66 su = User.find(4)
67
68 get '/users/current', {}, {'X-Redmine-API-Key' => user.api_key, 'X-Redmine-Switch-User' => su.login}
69 assert_response :success
70 assert_equal user, assigns(:user)
71 assert_equal user, User.current
72 end
32 73 end
General Comments 0
You need to be logged in to leave comments. Login now