annotate app/controllers/application_controller.rb @ 1459:cf78a7ade302 luisf

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