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