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