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