annotate app/controllers/application_controller.rb @ 1494:e248c7af89ec redmine-2.4

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