annotate .svn/pristine/2f/2f1f6f8262e47819e2d086a5c6cc0817e0e7d2b5.svn-base @ 1519:afce8026aaeb redmine-2.4-integration

Merge from branch "live"
author Chris Cannam
date Tue, 09 Sep 2014 09:34:53 +0100
parents cbb26bc654de
children
rev   line source
Chris@909 1 # Redmine - project management software
Chris@909 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
Chris@909 3 #
Chris@909 4 # This program is free software; you can redistribute it and/or
Chris@909 5 # modify it under the terms of the GNU General Public License
Chris@909 6 # as published by the Free Software Foundation; either version 2
Chris@909 7 # of the License, or (at your option) any later version.
Chris@909 8 #
Chris@909 9 # This program is distributed in the hope that it will be useful,
Chris@909 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@909 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@909 12 # GNU General Public License for more details.
Chris@909 13 #
Chris@909 14 # You should have received a copy of the GNU General Public License
Chris@909 15 # along with this program; if not, write to the Free Software
Chris@909 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@909 17
Chris@909 18 require 'uri'
Chris@909 19 require 'cgi'
Chris@909 20
Chris@909 21 class Unauthorized < Exception; end
Chris@909 22
Chris@909 23 class ApplicationController < ActionController::Base
Chris@909 24 include Redmine::I18n
Chris@909 25
Chris@909 26 layout 'base'
Chris@909 27 exempt_from_layout 'builder', 'rsb'
Chris@909 28
Chris@909 29 protect_from_forgery
Chris@909 30 def handle_unverified_request
Chris@909 31 super
Chris@909 32 cookies.delete(:autologin)
Chris@909 33 end
Chris@909 34 # Remove broken cookie after upgrade from 0.8.x (#4292)
Chris@909 35 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
Chris@909 36 # TODO: remove it when Rails is fixed
Chris@909 37 before_filter :delete_broken_cookies
Chris@909 38 def delete_broken_cookies
Chris@909 39 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
Chris@909 40 cookies.delete '_redmine_session'
Chris@909 41 redirect_to home_path
Chris@909 42 return false
Chris@909 43 end
Chris@909 44 end
Chris@909 45
Chris@909 46 before_filter :user_setup, :check_if_login_required, :set_localization
Chris@909 47 filter_parameter_logging :password
Chris@909 48
Chris@909 49 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
Chris@909 50 rescue_from ::Unauthorized, :with => :deny_access
Chris@909 51
Chris@909 52 include Redmine::Search::Controller
Chris@909 53 include Redmine::MenuManager::MenuController
Chris@909 54 helper Redmine::MenuManager::MenuHelper
Chris@909 55
Chris@909 56 Redmine::Scm::Base.all.each do |scm|
Chris@909 57 require_dependency "repository/#{scm.underscore}"
Chris@909 58 end
Chris@909 59
Chris@909 60 def user_setup
Chris@909 61 # Check the settings cache for each request
Chris@909 62 Setting.check_cache
Chris@909 63 # Find the current user
Chris@909 64 User.current = find_current_user
Chris@909 65 end
Chris@909 66
Chris@909 67 # Returns the current user or nil if no user is logged in
Chris@909 68 # and starts a session if needed
Chris@909 69 def find_current_user
Chris@909 70 if session[:user_id]
Chris@909 71 # existing session
Chris@909 72 (User.active.find(session[:user_id]) rescue nil)
Chris@909 73 elsif cookies[:autologin] && Setting.autologin?
Chris@909 74 # auto-login feature starts a new session
Chris@909 75 user = User.try_to_autologin(cookies[:autologin])
Chris@909 76 session[:user_id] = user.id if user
Chris@909 77 user
Chris@909 78 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
Chris@909 79 # RSS key authentication does not start a session
Chris@909 80 User.find_by_rss_key(params[:key])
Chris@909 81 elsif Setting.rest_api_enabled? && accept_api_auth?
Chris@909 82 if (key = api_key_from_request)
Chris@909 83 # Use API key
Chris@909 84 User.find_by_api_key(key)
Chris@909 85 else
Chris@909 86 # HTTP Basic, either username/password or API key/random
Chris@909 87 authenticate_with_http_basic do |username, password|
Chris@909 88 User.try_to_login(username, password) || User.find_by_api_key(username)
Chris@909 89 end
Chris@909 90 end
Chris@909 91 end
Chris@909 92 end
Chris@909 93
Chris@909 94 # Sets the logged in user
Chris@909 95 def logged_user=(user)
Chris@909 96 reset_session
Chris@909 97 if user && user.is_a?(User)
Chris@909 98 User.current = user
Chris@909 99 session[:user_id] = user.id
Chris@909 100 else
Chris@909 101 User.current = User.anonymous
Chris@909 102 end
Chris@909 103 end
Chris@909 104
Chris@909 105 # check if login is globally required to access the application
Chris@909 106 def check_if_login_required
Chris@909 107 # no check needed if user is already logged in
Chris@909 108 return true if User.current.logged?
Chris@909 109 require_login if Setting.login_required?
Chris@909 110 end
Chris@909 111
Chris@909 112 def set_localization
Chris@909 113 lang = nil
Chris@909 114 if User.current.logged?
Chris@909 115 lang = find_language(User.current.language)
Chris@909 116 end
Chris@909 117 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
Chris@909 118 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
Chris@909 119 if !accept_lang.blank?
Chris@909 120 accept_lang = accept_lang.downcase
Chris@909 121 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
Chris@909 122 end
Chris@909 123 end
Chris@909 124 lang ||= Setting.default_language
Chris@909 125 set_language_if_valid(lang)
Chris@909 126 end
Chris@909 127
Chris@909 128 def require_login
Chris@909 129 if !User.current.logged?
Chris@909 130 # Extract only the basic url parameters on non-GET requests
Chris@909 131 if request.get?
Chris@909 132 url = url_for(params)
Chris@909 133 else
Chris@909 134 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
Chris@909 135 end
Chris@909 136 respond_to do |format|
Chris@909 137 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
Chris@909 138 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
Chris@909 139 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
Chris@909 140 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
Chris@909 141 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
Chris@909 142 end
Chris@909 143 return false
Chris@909 144 end
Chris@909 145 true
Chris@909 146 end
Chris@909 147
Chris@909 148 def require_admin
Chris@909 149 return unless require_login
Chris@909 150 if !User.current.admin?
Chris@909 151 render_403
Chris@909 152 return false
Chris@909 153 end
Chris@909 154 true
Chris@909 155 end
Chris@909 156
Chris@909 157 def deny_access
Chris@909 158 User.current.logged? ? render_403 : require_login
Chris@909 159 end
Chris@909 160
Chris@909 161 # Authorize the user for the requested action
Chris@909 162 def authorize(ctrl = params[:controller], action = params[:action], global = false)
Chris@909 163 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
Chris@909 164 if allowed
Chris@909 165 true
Chris@909 166 else
Chris@909 167 if @project && @project.archived?
Chris@909 168 render_403 :message => :notice_not_authorized_archived_project
Chris@909 169 else
Chris@909 170 deny_access
Chris@909 171 end
Chris@909 172 end
Chris@909 173 end
Chris@909 174
Chris@909 175 # Authorize the user for the requested action outside a project
Chris@909 176 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
Chris@909 177 authorize(ctrl, action, global)
Chris@909 178 end
Chris@909 179
Chris@909 180 # Find project of id params[:id]
Chris@909 181 def find_project
Chris@909 182 @project = Project.find(params[:id])
Chris@909 183 rescue ActiveRecord::RecordNotFound
Chris@909 184 render_404
Chris@909 185 end
Chris@909 186
Chris@909 187 # Find project of id params[:project_id]
Chris@909 188 def find_project_by_project_id
Chris@909 189 @project = Project.find(params[:project_id])
Chris@909 190 rescue ActiveRecord::RecordNotFound
Chris@909 191 render_404
Chris@909 192 end
Chris@909 193
Chris@909 194 # Find a project based on params[:project_id]
Chris@909 195 # TODO: some subclasses override this, see about merging their logic
Chris@909 196 def find_optional_project
Chris@909 197 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
Chris@909 198 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
Chris@909 199 allowed ? true : deny_access
Chris@909 200 rescue ActiveRecord::RecordNotFound
Chris@909 201 render_404
Chris@909 202 end
Chris@909 203
Chris@909 204 # Finds and sets @project based on @object.project
Chris@909 205 def find_project_from_association
Chris@909 206 render_404 unless @object.present?
Chris@909 207
Chris@909 208 @project = @object.project
Chris@909 209 end
Chris@909 210
Chris@909 211 def find_model_object
Chris@909 212 model = self.class.read_inheritable_attribute('model_object')
Chris@909 213 if model
Chris@909 214 @object = model.find(params[:id])
Chris@909 215 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
Chris@909 216 end
Chris@909 217 rescue ActiveRecord::RecordNotFound
Chris@909 218 render_404
Chris@909 219 end
Chris@909 220
Chris@909 221 def self.model_object(model)
Chris@909 222 write_inheritable_attribute('model_object', model)
Chris@909 223 end
Chris@909 224
Chris@909 225 # Filter for bulk issue operations
Chris@909 226 def find_issues
Chris@909 227 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
Chris@909 228 raise ActiveRecord::RecordNotFound if @issues.empty?
Chris@909 229 if @issues.detect {|issue| !issue.visible?}
Chris@909 230 deny_access
Chris@909 231 return
Chris@909 232 end
Chris@909 233 @projects = @issues.collect(&:project).compact.uniq
Chris@909 234 @project = @projects.first if @projects.size == 1
Chris@909 235 rescue ActiveRecord::RecordNotFound
Chris@909 236 render_404
Chris@909 237 end
Chris@909 238
Chris@909 239 # Check if project is unique before bulk operations
Chris@909 240 def check_project_uniqueness
Chris@909 241 unless @project
Chris@909 242 # TODO: let users bulk edit/move/destroy issues from different projects
Chris@909 243 render_error 'Can not bulk edit/move/destroy issues from different projects'
Chris@909 244 return false
Chris@909 245 end
Chris@909 246 end
Chris@909 247
Chris@909 248 # make sure that the user is a member of the project (or admin) if project is private
Chris@909 249 # used as a before_filter for actions that do not require any particular permission on the project
Chris@909 250 def check_project_privacy
Chris@909 251 if @project && @project.active?
Chris@909 252 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
Chris@909 253 true
Chris@909 254 else
Chris@909 255 deny_access
Chris@909 256 end
Chris@909 257 else
Chris@909 258 @project = nil
Chris@909 259 render_404
Chris@909 260 false
Chris@909 261 end
Chris@909 262 end
Chris@909 263
Chris@909 264 def back_url
Chris@909 265 params[:back_url] || request.env['HTTP_REFERER']
Chris@909 266 end
Chris@909 267
Chris@909 268 def redirect_back_or_default(default)
Chris@909 269 back_url = CGI.unescape(params[:back_url].to_s)
Chris@909 270 if !back_url.blank?
Chris@909 271 begin
Chris@909 272 uri = URI.parse(back_url)
Chris@909 273 # do not redirect user to another host or to the login or register page
Chris@909 274 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
Chris@909 275 redirect_to(back_url)
Chris@909 276 return
Chris@909 277 end
Chris@909 278 rescue URI::InvalidURIError
Chris@909 279 # redirect to default
Chris@909 280 end
Chris@909 281 end
Chris@909 282 redirect_to default
Chris@909 283 false
Chris@909 284 end
Chris@909 285
Chris@909 286 def render_403(options={})
Chris@909 287 @project = nil
Chris@909 288 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
Chris@909 289 return false
Chris@909 290 end
Chris@909 291
Chris@909 292 def render_404(options={})
Chris@909 293 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
Chris@909 294 return false
Chris@909 295 end
Chris@909 296
Chris@909 297 # Renders an error response
Chris@909 298 def render_error(arg)
Chris@909 299 arg = {:message => arg} unless arg.is_a?(Hash)
Chris@909 300
Chris@909 301 @message = arg[:message]
Chris@909 302 @message = l(@message) if @message.is_a?(Symbol)
Chris@909 303 @status = arg[:status] || 500
Chris@909 304
Chris@909 305 respond_to do |format|
Chris@909 306 format.html {
Chris@909 307 render :template => 'common/error', :layout => use_layout, :status => @status
Chris@909 308 }
Chris@909 309 format.atom { head @status }
Chris@909 310 format.xml { head @status }
Chris@909 311 format.js { head @status }
Chris@909 312 format.json { head @status }
Chris@909 313 end
Chris@909 314 end
Chris@909 315
Chris@909 316 # Filter for actions that provide an API response
Chris@909 317 # but have no HTML representation for non admin users
Chris@909 318 def require_admin_or_api_request
Chris@909 319 return true if api_request?
Chris@909 320 if User.current.admin?
Chris@909 321 true
Chris@909 322 elsif User.current.logged?
Chris@909 323 render_error(:status => 406)
Chris@909 324 else
Chris@909 325 deny_access
Chris@909 326 end
Chris@909 327 end
Chris@909 328
Chris@909 329 # Picks which layout to use based on the request
Chris@909 330 #
Chris@909 331 # @return [boolean, string] name of the layout to use or false for no layout
Chris@909 332 def use_layout
Chris@909 333 request.xhr? ? false : 'base'
Chris@909 334 end
Chris@909 335
Chris@909 336 def invalid_authenticity_token
Chris@909 337 if api_request?
Chris@909 338 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
Chris@909 339 end
Chris@909 340 render_error "Invalid form authenticity token."
Chris@909 341 end
Chris@909 342
Chris@909 343 def render_feed(items, options={})
Chris@909 344 @items = items || []
Chris@909 345 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
Chris@909 346 @items = @items.slice(0, Setting.feeds_limit.to_i)
Chris@909 347 @title = options[:title] || Setting.app_title
Chris@909 348 render :template => "common/feed.atom", :layout => false,
Chris@909 349 :content_type => 'application/atom+xml'
Chris@909 350 end
Chris@909 351
Chris@909 352 # TODO: remove in Redmine 1.4
Chris@909 353 def self.accept_key_auth(*actions)
Chris@909 354 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
Chris@909 355 accept_rss_auth(*actions)
Chris@909 356 end
Chris@909 357
Chris@909 358 # TODO: remove in Redmine 1.4
Chris@909 359 def accept_key_auth_actions
Chris@909 360 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth_actions is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
Chris@909 361 self.class.accept_rss_auth
Chris@909 362 end
Chris@909 363
Chris@909 364 def self.accept_rss_auth(*actions)
Chris@909 365 if actions.any?
Chris@909 366 write_inheritable_attribute('accept_rss_auth_actions', actions)
Chris@909 367 else
Chris@909 368 read_inheritable_attribute('accept_rss_auth_actions') || []
Chris@909 369 end
Chris@909 370 end
Chris@909 371
Chris@909 372 def accept_rss_auth?(action=action_name)
Chris@909 373 self.class.accept_rss_auth.include?(action.to_sym)
Chris@909 374 end
Chris@909 375
Chris@909 376 def self.accept_api_auth(*actions)
Chris@909 377 if actions.any?
Chris@909 378 write_inheritable_attribute('accept_api_auth_actions', actions)
Chris@909 379 else
Chris@909 380 read_inheritable_attribute('accept_api_auth_actions') || []
Chris@909 381 end
Chris@909 382 end
Chris@909 383
Chris@909 384 def accept_api_auth?(action=action_name)
Chris@909 385 self.class.accept_api_auth.include?(action.to_sym)
Chris@909 386 end
Chris@909 387
Chris@909 388 # Returns the number of objects that should be displayed
Chris@909 389 # on the paginated list
Chris@909 390 def per_page_option
Chris@909 391 per_page = nil
Chris@909 392 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
Chris@909 393 per_page = params[:per_page].to_s.to_i
Chris@909 394 session[:per_page] = per_page
Chris@909 395 elsif session[:per_page]
Chris@909 396 per_page = session[:per_page]
Chris@909 397 else
Chris@909 398 per_page = Setting.per_page_options_array.first || 25
Chris@909 399 end
Chris@909 400 per_page
Chris@909 401 end
Chris@909 402
Chris@909 403 # Returns offset and limit used to retrieve objects
Chris@909 404 # for an API response based on offset, limit and page parameters
Chris@909 405 def api_offset_and_limit(options=params)
Chris@909 406 if options[:offset].present?
Chris@909 407 offset = options[:offset].to_i
Chris@909 408 if offset < 0
Chris@909 409 offset = 0
Chris@909 410 end
Chris@909 411 end
Chris@909 412 limit = options[:limit].to_i
Chris@909 413 if limit < 1
Chris@909 414 limit = 25
Chris@909 415 elsif limit > 100
Chris@909 416 limit = 100
Chris@909 417 end
Chris@909 418 if offset.nil? && options[:page].present?
Chris@909 419 offset = (options[:page].to_i - 1) * limit
Chris@909 420 offset = 0 if offset < 0
Chris@909 421 end
Chris@909 422 offset ||= 0
Chris@909 423
Chris@909 424 [offset, limit]
Chris@909 425 end
Chris@909 426
Chris@909 427 # qvalues http header parser
Chris@909 428 # code taken from webrick
Chris@909 429 def parse_qvalues(value)
Chris@909 430 tmp = []
Chris@909 431 if value
Chris@909 432 parts = value.split(/,\s*/)
Chris@909 433 parts.each {|part|
Chris@909 434 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
Chris@909 435 val = m[1]
Chris@909 436 q = (m[2] or 1).to_f
Chris@909 437 tmp.push([val, q])
Chris@909 438 end
Chris@909 439 }
Chris@909 440 tmp = tmp.sort_by{|val, q| -q}
Chris@909 441 tmp.collect!{|val, q| val}
Chris@909 442 end
Chris@909 443 return tmp
Chris@909 444 rescue
Chris@909 445 nil
Chris@909 446 end
Chris@909 447
Chris@909 448 # Returns a string that can be used as filename value in Content-Disposition header
Chris@909 449 def filename_for_content_disposition(name)
Chris@909 450 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
Chris@909 451 end
Chris@909 452
Chris@909 453 def api_request?
Chris@909 454 %w(xml json).include? params[:format]
Chris@909 455 end
Chris@909 456
Chris@909 457 # Returns the API key present in the request
Chris@909 458 def api_key_from_request
Chris@909 459 if params[:key].present?
Chris@909 460 params[:key]
Chris@909 461 elsif request.headers["X-Redmine-API-Key"].present?
Chris@909 462 request.headers["X-Redmine-API-Key"]
Chris@909 463 end
Chris@909 464 end
Chris@909 465
Chris@909 466 # Renders a warning flash if obj has unsaved attachments
Chris@909 467 def render_attachment_warning_if_needed(obj)
Chris@909 468 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
Chris@909 469 end
Chris@909 470
Chris@909 471 # Sets the `flash` notice or error based the number of issues that did not save
Chris@909 472 #
Chris@909 473 # @param [Array, Issue] issues all of the saved and unsaved Issues
Chris@909 474 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
Chris@909 475 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
Chris@909 476 if unsaved_issue_ids.empty?
Chris@909 477 flash[:notice] = l(:notice_successful_update) unless issues.empty?
Chris@909 478 else
Chris@909 479 flash[:error] = l(:notice_failed_to_save_issues,
Chris@909 480 :count => unsaved_issue_ids.size,
Chris@909 481 :total => issues.size,
Chris@909 482 :ids => '#' + unsaved_issue_ids.join(', #'))
Chris@909 483 end
Chris@909 484 end
Chris@909 485
Chris@909 486 # Rescues an invalid query statement. Just in case...
Chris@909 487 def query_statement_invalid(exception)
Chris@909 488 logger.error "Query::StatementInvalid: #{exception.message}" if logger
Chris@909 489 session.delete(:query)
Chris@909 490 sort_clear if respond_to?(:sort_clear)
Chris@909 491 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
Chris@909 492 end
Chris@909 493
Chris@909 494 # Renders API response on validation failure
Chris@909 495 def render_validation_errors(object)
Chris@909 496 options = { :status => :unprocessable_entity, :layout => false }
Chris@909 497 options.merge!(case params[:format]
Chris@909 498 when 'xml'; { :xml => object.errors }
Chris@909 499 when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance
Chris@909 500 else
Chris@909 501 raise "Unknown format #{params[:format]} in #render_validation_errors"
Chris@909 502 end
Chris@909 503 )
Chris@909 504 render options
Chris@909 505 end
Chris@909 506
Chris@909 507 # Overrides #default_template so that the api template
Chris@909 508 # is used automatically if it exists
Chris@909 509 def default_template(action_name = self.action_name)
Chris@909 510 if api_request?
Chris@909 511 begin
Chris@909 512 return self.view_paths.find_template(default_template_name(action_name), 'api')
Chris@909 513 rescue ::ActionView::MissingTemplate
Chris@909 514 # the api template was not found
Chris@909 515 # fallback to the default behaviour
Chris@909 516 end
Chris@909 517 end
Chris@909 518 super
Chris@909 519 end
Chris@909 520
Chris@909 521 # Overrides #pick_layout so that #render with no arguments
Chris@909 522 # doesn't use the layout for api requests
Chris@909 523 def pick_layout(*args)
Chris@909 524 api_request? ? nil : super
Chris@909 525 end
Chris@909 526 end