comparison .svn/pristine/c5/c58c8e6ce884b34a42a4036c1723c49ce867318b.svn-base @ 1517:dffacf8a6908 redmine-2.5

Update to Redmine SVN revision 13367 on 2.5-stable branch
author Chris Cannam
date Tue, 09 Sep 2014 09:29:00 +0100
parents
children
comparison
equal deleted inserted replaced
1516:b450a9d58aed 1517:dffacf8a6908
1 # Redmine - project management software
2 # Copyright (C) 2006-2014 Jean-Philippe Lang
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 require 'uri'
19 require 'cgi'
20
21 class Unauthorized < Exception; end
22
23 class ApplicationController < ActionController::Base
24 include Redmine::I18n
25 include Redmine::Pagination
26 include RoutesHelper
27 helper :routes
28
29 class_attribute :accept_api_auth_actions
30 class_attribute :accept_rss_auth_actions
31 class_attribute :model_object
32
33 layout 'base'
34
35 protect_from_forgery
36
37 def verify_authenticity_token
38 unless api_request?
39 super
40 end
41 end
42
43 def handle_unverified_request
44 unless api_request?
45 super
46 cookies.delete(autologin_cookie_name)
47 self.logged_user = nil
48 render_error :status => 422, :message => "Invalid form authenticity token."
49 end
50 end
51
52 before_filter :session_expiration, :user_setup, :check_if_login_required, :check_password_change, :set_localization
53
54 rescue_from ::Unauthorized, :with => :deny_access
55 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
56
57 include Redmine::Search::Controller
58 include Redmine::MenuManager::MenuController
59 helper Redmine::MenuManager::MenuHelper
60
61 def session_expiration
62 if session[:user_id]
63 if session_expired? && !try_to_autologin
64 reset_session
65 flash[:error] = l(:error_session_expired)
66 redirect_to signin_url
67 else
68 session[:atime] = Time.now.utc.to_i
69 end
70 end
71 end
72
73 def session_expired?
74 if Setting.session_lifetime?
75 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
76 return true
77 end
78 end
79 if Setting.session_timeout?
80 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
81 return true
82 end
83 end
84 false
85 end
86
87 def start_user_session(user)
88 session[:user_id] = user.id
89 session[:ctime] = Time.now.utc.to_i
90 session[:atime] = Time.now.utc.to_i
91 if user.must_change_password?
92 session[:pwd] = '1'
93 end
94 end
95
96 def user_setup
97 # Check the settings cache for each request
98 Setting.check_cache
99 # Find the current user
100 User.current = find_current_user
101 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
102 end
103
104 # Returns the current user or nil if no user is logged in
105 # and starts a session if needed
106 def find_current_user
107 user = nil
108 unless api_request?
109 if session[:user_id]
110 # existing session
111 user = (User.active.find(session[:user_id]) rescue nil)
112 elsif autologin_user = try_to_autologin
113 user = autologin_user
114 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
115 # RSS key authentication does not start a session
116 user = User.find_by_rss_key(params[:key])
117 end
118 end
119 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
120 if (key = api_key_from_request)
121 # Use API key
122 user = User.find_by_api_key(key)
123 elsif request.authorization.to_s =~ /\ABasic /i
124 # HTTP Basic, either username/password or API key/random
125 authenticate_with_http_basic do |username, password|
126 user = User.try_to_login(username, password) || User.find_by_api_key(username)
127 end
128 if user && user.must_change_password?
129 render_error :message => 'You must change your password', :status => 403
130 return
131 end
132 end
133 # Switch user if requested by an admin user
134 if user && user.admin? && (username = api_switch_user_from_request)
135 su = User.find_by_login(username)
136 if su && su.active?
137 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
138 user = su
139 else
140 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
141 end
142 end
143 end
144 user
145 end
146
147 def autologin_cookie_name
148 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
149 end
150
151 def try_to_autologin
152 if cookies[autologin_cookie_name] && Setting.autologin?
153 # auto-login feature starts a new session
154 user = User.try_to_autologin(cookies[autologin_cookie_name])
155 if user
156 reset_session
157 start_user_session(user)
158 end
159 user
160 end
161 end
162
163 # Sets the logged in user
164 def logged_user=(user)
165 reset_session
166 if user && user.is_a?(User)
167 User.current = user
168 start_user_session(user)
169 else
170 User.current = User.anonymous
171 end
172 end
173
174 # Logs out current user
175 def logout_user
176 if User.current.logged?
177 cookies.delete(autologin_cookie_name)
178 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
179 self.logged_user = nil
180 end
181 end
182
183 # check if login is globally required to access the application
184 def check_if_login_required
185 # no check needed if user is already logged in
186 return true if User.current.logged?
187 require_login if Setting.login_required?
188 end
189
190 def check_password_change
191 if session[:pwd]
192 if User.current.must_change_password?
193 redirect_to my_password_path
194 else
195 session.delete(:pwd)
196 end
197 end
198 end
199
200 def set_localization
201 lang = nil
202 if User.current.logged?
203 lang = find_language(User.current.language)
204 end
205 if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
206 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
207 if !accept_lang.blank?
208 accept_lang = accept_lang.downcase
209 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
210 end
211 end
212 lang ||= Setting.default_language
213 set_language_if_valid(lang)
214 end
215
216 def require_login
217 if !User.current.logged?
218 # Extract only the basic url parameters on non-GET requests
219 if request.get?
220 url = url_for(params)
221 else
222 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
223 end
224 respond_to do |format|
225 format.html {
226 if request.xhr?
227 head :unauthorized
228 else
229 redirect_to :controller => "account", :action => "login", :back_url => url
230 end
231 }
232 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
233 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
234 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
235 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
236 end
237 return false
238 end
239 true
240 end
241
242 def require_admin
243 return unless require_login
244 if !User.current.admin?
245 render_403
246 return false
247 end
248 true
249 end
250
251 def deny_access
252 User.current.logged? ? render_403 : require_login
253 end
254
255 # Authorize the user for the requested action
256 def authorize(ctrl = params[:controller], action = params[:action], global = false)
257 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
258 if allowed
259 true
260 else
261 if @project && @project.archived?
262 render_403 :message => :notice_not_authorized_archived_project
263 else
264 deny_access
265 end
266 end
267 end
268
269 # Authorize the user for the requested action outside a project
270 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
271 authorize(ctrl, action, global)
272 end
273
274 # Find project of id params[:id]
275 def find_project
276 @project = Project.find(params[:id])
277 rescue ActiveRecord::RecordNotFound
278 render_404
279 end
280
281 # Find project of id params[:project_id]
282 def find_project_by_project_id
283 @project = Project.find(params[:project_id])
284 rescue ActiveRecord::RecordNotFound
285 render_404
286 end
287
288 # Find a project based on params[:project_id]
289 # TODO: some subclasses override this, see about merging their logic
290 def find_optional_project
291 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
292 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
293 allowed ? true : deny_access
294 rescue ActiveRecord::RecordNotFound
295 render_404
296 end
297
298 # Finds and sets @project based on @object.project
299 def find_project_from_association
300 render_404 unless @object.present?
301
302 @project = @object.project
303 end
304
305 def find_model_object
306 model = self.class.model_object
307 if model
308 @object = model.find(params[:id])
309 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
310 end
311 rescue ActiveRecord::RecordNotFound
312 render_404
313 end
314
315 def self.model_object(model)
316 self.model_object = model
317 end
318
319 # Find the issue whose id is the :id parameter
320 # Raises a Unauthorized exception if the issue is not visible
321 def find_issue
322 # Issue.visible.find(...) can not be used to redirect user to the login form
323 # if the issue actually exists but requires authentication
324 @issue = Issue.find(params[:id])
325 raise Unauthorized unless @issue.visible?
326 @project = @issue.project
327 rescue ActiveRecord::RecordNotFound
328 render_404
329 end
330
331 # Find issues with a single :id param or :ids array param
332 # Raises a Unauthorized exception if one of the issues is not visible
333 def find_issues
334 @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
335 raise ActiveRecord::RecordNotFound if @issues.empty?
336 raise Unauthorized unless @issues.all?(&:visible?)
337 @projects = @issues.collect(&:project).compact.uniq
338 @project = @projects.first if @projects.size == 1
339 rescue ActiveRecord::RecordNotFound
340 render_404
341 end
342
343 def find_attachments
344 if (attachments = params[:attachments]).present?
345 att = attachments.values.collect do |attachment|
346 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
347 end
348 att.compact!
349 end
350 @attachments = att || []
351 end
352
353 # make sure that the user is a member of the project (or admin) if project is private
354 # used as a before_filter for actions that do not require any particular permission on the project
355 def check_project_privacy
356 if @project && !@project.archived?
357 if @project.visible?
358 true
359 else
360 deny_access
361 end
362 else
363 @project = nil
364 render_404
365 false
366 end
367 end
368
369 def back_url
370 url = params[:back_url]
371 if url.nil? && referer = request.env['HTTP_REFERER']
372 url = CGI.unescape(referer.to_s)
373 end
374 url
375 end
376
377 def redirect_back_or_default(default, options={})
378 back_url = params[:back_url].to_s
379 if back_url.present? && valid_back_url?(back_url)
380 redirect_to(back_url)
381 return
382 elsif options[:referer]
383 redirect_to_referer_or default
384 return
385 end
386 redirect_to default
387 false
388 end
389
390 # Returns true if back_url is a valid url for redirection, otherwise false
391 def valid_back_url?(back_url)
392 if CGI.unescape(back_url).include?('..')
393 return false
394 end
395
396 begin
397 uri = URI.parse(back_url)
398 rescue URI::InvalidURIError
399 return false
400 end
401
402 if uri.host.present? && uri.host != request.host
403 return false
404 end
405
406 if uri.path.match(%r{/(login|account/register)})
407 return false
408 end
409
410 if relative_url_root.present? && !uri.path.starts_with?(relative_url_root)
411 return false
412 end
413
414 return true
415 end
416 private :valid_back_url?
417
418 # Redirects to the request referer if present, redirects to args or call block otherwise.
419 def redirect_to_referer_or(*args, &block)
420 redirect_to :back
421 rescue ::ActionController::RedirectBackError
422 if args.any?
423 redirect_to *args
424 elsif block_given?
425 block.call
426 else
427 raise "#redirect_to_referer_or takes arguments or a block"
428 end
429 end
430
431 def render_403(options={})
432 @project = nil
433 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
434 return false
435 end
436
437 def render_404(options={})
438 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
439 return false
440 end
441
442 # Renders an error response
443 def render_error(arg)
444 arg = {:message => arg} unless arg.is_a?(Hash)
445
446 @message = arg[:message]
447 @message = l(@message) if @message.is_a?(Symbol)
448 @status = arg[:status] || 500
449
450 respond_to do |format|
451 format.html {
452 render :template => 'common/error', :layout => use_layout, :status => @status
453 }
454 format.any { head @status }
455 end
456 end
457
458 # Handler for ActionView::MissingTemplate exception
459 def missing_template
460 logger.warn "Missing template, responding with 404"
461 @project = nil
462 render_404
463 end
464
465 # Filter for actions that provide an API response
466 # but have no HTML representation for non admin users
467 def require_admin_or_api_request
468 return true if api_request?
469 if User.current.admin?
470 true
471 elsif User.current.logged?
472 render_error(:status => 406)
473 else
474 deny_access
475 end
476 end
477
478 # Picks which layout to use based on the request
479 #
480 # @return [boolean, string] name of the layout to use or false for no layout
481 def use_layout
482 request.xhr? ? false : 'base'
483 end
484
485 def render_feed(items, options={})
486 @items = items || []
487 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
488 @items = @items.slice(0, Setting.feeds_limit.to_i)
489 @title = options[:title] || Setting.app_title
490 render :template => "common/feed", :formats => [:atom], :layout => false,
491 :content_type => 'application/atom+xml'
492 end
493
494 def self.accept_rss_auth(*actions)
495 if actions.any?
496 self.accept_rss_auth_actions = actions
497 else
498 self.accept_rss_auth_actions || []
499 end
500 end
501
502 def accept_rss_auth?(action=action_name)
503 self.class.accept_rss_auth.include?(action.to_sym)
504 end
505
506 def self.accept_api_auth(*actions)
507 if actions.any?
508 self.accept_api_auth_actions = actions
509 else
510 self.accept_api_auth_actions || []
511 end
512 end
513
514 def accept_api_auth?(action=action_name)
515 self.class.accept_api_auth.include?(action.to_sym)
516 end
517
518 # Returns the number of objects that should be displayed
519 # on the paginated list
520 def per_page_option
521 per_page = nil
522 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
523 per_page = params[:per_page].to_s.to_i
524 session[:per_page] = per_page
525 elsif session[:per_page]
526 per_page = session[:per_page]
527 else
528 per_page = Setting.per_page_options_array.first || 25
529 end
530 per_page
531 end
532
533 # Returns offset and limit used to retrieve objects
534 # for an API response based on offset, limit and page parameters
535 def api_offset_and_limit(options=params)
536 if options[:offset].present?
537 offset = options[:offset].to_i
538 if offset < 0
539 offset = 0
540 end
541 end
542 limit = options[:limit].to_i
543 if limit < 1
544 limit = 25
545 elsif limit > 100
546 limit = 100
547 end
548 if offset.nil? && options[:page].present?
549 offset = (options[:page].to_i - 1) * limit
550 offset = 0 if offset < 0
551 end
552 offset ||= 0
553
554 [offset, limit]
555 end
556
557 # qvalues http header parser
558 # code taken from webrick
559 def parse_qvalues(value)
560 tmp = []
561 if value
562 parts = value.split(/,\s*/)
563 parts.each {|part|
564 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
565 val = m[1]
566 q = (m[2] or 1).to_f
567 tmp.push([val, q])
568 end
569 }
570 tmp = tmp.sort_by{|val, q| -q}
571 tmp.collect!{|val, q| val}
572 end
573 return tmp
574 rescue
575 nil
576 end
577
578 # Returns a string that can be used as filename value in Content-Disposition header
579 def filename_for_content_disposition(name)
580 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
581 end
582
583 def api_request?
584 %w(xml json).include? params[:format]
585 end
586
587 # Returns the API key present in the request
588 def api_key_from_request
589 if params[:key].present?
590 params[:key].to_s
591 elsif request.headers["X-Redmine-API-Key"].present?
592 request.headers["X-Redmine-API-Key"].to_s
593 end
594 end
595
596 # Returns the API 'switch user' value if present
597 def api_switch_user_from_request
598 request.headers["X-Redmine-Switch-User"].to_s.presence
599 end
600
601 # Renders a warning flash if obj has unsaved attachments
602 def render_attachment_warning_if_needed(obj)
603 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
604 end
605
606 # Rescues an invalid query statement. Just in case...
607 def query_statement_invalid(exception)
608 logger.error "Query::StatementInvalid: #{exception.message}" if logger
609 session.delete(:query)
610 sort_clear if respond_to?(:sort_clear)
611 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
612 end
613
614 # Renders a 200 response for successfull updates or deletions via the API
615 def render_api_ok
616 render_api_head :ok
617 end
618
619 # Renders a head API response
620 def render_api_head(status)
621 # #head would return a response body with one space
622 render :text => '', :status => status, :layout => nil
623 end
624
625 # Renders API response on validation failure
626 def render_validation_errors(objects)
627 if objects.is_a?(Array)
628 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
629 else
630 @error_messages = objects.errors.full_messages
631 end
632 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
633 end
634
635 # Overrides #_include_layout? so that #render with no arguments
636 # doesn't use the layout for api requests
637 def _include_layout?(*args)
638 api_request? ? false : super
639 end
640 end