annotate app/controllers/application_controller.rb @ 1600:ed9c467ef922 dockerise

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