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