Class: ApplicationController

Inherits:
ActionController::Base
  • Object
show all
Includes:
Redmine::I18n, Redmine::MenuManager::MenuController, Redmine::Pagination, Redmine::Search::Controller, RoutesHelper
Defined in:
app/controllers/application_controller.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Redmine::MenuManager::MenuController

#current_menu_item, included, #menu_items, #redirect_to_project_menu_item

Methods included from Redmine::Search::Controller

#default_search_scope, #default_search_scopes, included

Methods included from RoutesHelper

#_new_time_entry_path, #_project_calendar_path, #_project_gantt_path, #_project_issues_path, #_report_time_entries_path, #_time_entries_path

Methods included from Redmine::Pagination

#deprecated_paginate, #paginate, #paginator

Methods included from Redmine::I18n

#current_language, #day_letter, #day_name, #find_language, #format_date, #format_time, included, #l, #l_hours, #l_or_humanize, #languages_options, #ll, #month_name, #set_language_if_valid, #valid_languages

Class Method Details

.accept_api_auth(*actions) ⇒ Object


520
521
522
523
524
525
526
# File 'app/controllers/application_controller.rb', line 520

def self.accept_api_auth(*actions)
  if actions.any?
    self.accept_api_auth_actions = actions
  else
    self.accept_api_auth_actions || []
  end
end

.accept_rss_auth(*actions) ⇒ Object


508
509
510
511
512
513
514
# File 'app/controllers/application_controller.rb', line 508

def self.accept_rss_auth(*actions)
  if actions.any?
    self.accept_rss_auth_actions = actions
  else
    self.accept_rss_auth_actions || []
  end
end

.model_object(model) ⇒ Object


329
330
331
# File 'app/controllers/application_controller.rb', line 329

def self.model_object(model)
  self.model_object = model
end

Instance Method Details

#_include_layout?(*args) ⇒ Boolean

Overrides #_include_layout? so that #render with no arguments doesn't use the layout for api requests

Returns:

  • (Boolean)

651
652
653
# File 'app/controllers/application_controller.rb', line 651

def _include_layout?(*args)
  api_request? ? false : super
end

#accept_api_auth?(action = action_name) ⇒ Boolean

Returns:

  • (Boolean)

528
529
530
# File 'app/controllers/application_controller.rb', line 528

def accept_api_auth?(action=action_name)
  self.class.accept_api_auth.include?(action.to_sym)
end

#accept_rss_auth?(action = action_name) ⇒ Boolean

Returns:

  • (Boolean)

516
517
518
# File 'app/controllers/application_controller.rb', line 516

def accept_rss_auth?(action=action_name)
  self.class.accept_rss_auth.include?(action.to_sym)
end

#api_key_from_requestObject

Returns the API key present in the request


602
603
604
605
606
607
608
# File 'app/controllers/application_controller.rb', line 602

def api_key_from_request
  if params[:key].present?
    params[:key].to_s
  elsif request.headers["X-Redmine-API-Key"].present?
    request.headers["X-Redmine-API-Key"].to_s
  end
end

#api_offset_and_limit(options = params) ⇒ Object

Returns offset and limit used to retrieve objects for an API response based on offset, limit and page parameters


549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'app/controllers/application_controller.rb', line 549

def api_offset_and_limit(options=params)
  if options[:offset].present?
    offset = options[:offset].to_i
    if offset < 0
      offset = 0
    end
  end
  limit = options[:limit].to_i
  if limit < 1
    limit = 25
  elsif limit > 100
    limit = 100
  end
  if offset.nil? && options[:page].present?
    offset = (options[:page].to_i - 1) * limit
    offset = 0 if offset < 0
  end
  offset ||= 0

  [offset, limit]
end

#api_request?Boolean

Returns:

  • (Boolean)

597
598
599
# File 'app/controllers/application_controller.rb', line 597

def api_request?
  %w(xml json).include? params[:format]
end

#api_switch_user_from_requestObject

Returns the API 'switch user' value if present


611
612
613
# File 'app/controllers/application_controller.rb', line 611

def api_switch_user_from_request
  request.headers["X-Redmine-Switch-User"].to_s.presence
end

#authorize(ctrl = params[:controller], action = params[:action], global = false) ⇒ Object

Authorize the user for the requested action


270
271
272
273
274
275
276
277
278
279
280
281
# File 'app/controllers/application_controller.rb', line 270

def authorize(ctrl = params[:controller], action = params[:action], global = false)
  allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
  if allowed
    true
  else
    if @project && @project.archived?
      render_403 :message => :notice_not_authorized_archived_project
    else
      deny_access
    end
  end
end

#authorize_global(ctrl = params[:controller], action = params[:action], global = true) ⇒ Object

Authorize the user for the requested action outside a project


284
285
286
# File 'app/controllers/application_controller.rb', line 284

def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
  authorize(ctrl, action, global)
end

161
162
163
# File 'app/controllers/application_controller.rb', line 161

def autologin_cookie_name
  Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
end

#back_urlObject


383
384
385
386
387
388
389
# File 'app/controllers/application_controller.rb', line 383

def back_url
  url = params[:back_url]
  if url.nil? && referer = request.env['HTTP_REFERER']
    url = CGI.unescape(referer.to_s)
  end
  url
end

#check_if_login_requiredObject

check if login is globally required to access the application


198
199
200
201
202
# File 'app/controllers/application_controller.rb', line 198

def 
  # no check needed if user is already logged in
  return true if User.current.logged?
   if Setting.
end

#check_password_changeObject


204
205
206
207
208
209
210
211
212
# File 'app/controllers/application_controller.rb', line 204

def check_password_change
  if session[:pwd]
    if User.current.must_change_password?
      redirect_to my_password_path
    else
      session.delete(:pwd)
    end
  end
end

#check_project_privacyObject

make sure that the user is a member of the project (or admin) if project is private used as a before_filter for actions that do not require any particular permission on the project


369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'app/controllers/application_controller.rb', line 369

def check_project_privacy
  if @project && !@project.archived?
    if @project.visible?
      true
    else
      deny_access
    end
  else
    @project = nil
    render_404
    false
  end
end

#deny_accessObject


265
266
267
# File 'app/controllers/application_controller.rb', line 265

def deny_access
  User.current.logged? ? render_403 : 
end

#filename_for_content_disposition(name) ⇒ Object

Returns a string that can be used as filename value in Content-Disposition header


593
594
595
# File 'app/controllers/application_controller.rb', line 593

def filename_for_content_disposition(name)
  request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
end

#find_attachmentsObject


357
358
359
360
361
362
363
364
365
# File 'app/controllers/application_controller.rb', line 357

def find_attachments
  if (attachments = params[:attachments]).present?
    att = attachments.values.collect do |attachment|
      Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
    end
    att.compact!
  end
  @attachments = att || []
end

#find_current_userObject

Returns the current user or nil if no user is logged in and starts a session if needed


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'app/controllers/application_controller.rb', line 108

def find_current_user
  user = nil
  unless api_request?
    if session[:user_id]
      # existing session
      user = (User.active.find(session[:user_id]) rescue nil)
    elsif autologin_user = try_to_autologin
      user = autologin_user
    elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
      # RSS key authentication does not start a session
      user = User.find_by_rss_key(params[:key])
    end
  end
  if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
    if (key = api_key_from_request)
      # Use API key
      user = User.find_by_api_key(key)
    elsif request.authorization.to_s =~ /\ABasic /i
      # HTTP Basic, either username/password or API key/random
      authenticate_with_http_basic do |username, password|
        user = User.(username, password) || User.find_by_api_key(username)
      end
      if user && user.must_change_password?
        render_error :message => 'You must change your password', :status => 403
        return
      end
    end
    # Switch user if requested by an admin user
    if user && user.admin? && (username = api_switch_user_from_request)
      su = User.(username)
      if su && su.active?
        logger.info("  User switched by: #{user.} (id=#{user.id})") if logger
        user = su
      else
        render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
      end
    end
  end
  user
end

#find_issueObject

Find the issue whose id is the :id parameter Raises a Unauthorized exception if the issue is not visible


335
336
337
338
339
340
341
342
343
# File 'app/controllers/application_controller.rb', line 335

def find_issue
  # Issue.visible.find(...) can not be used to redirect user to the login form
  # if the issue actually exists but requires authentication
  @issue = Issue.find(params[:id])
  raise Unauthorized unless @issue.visible?
  @project = @issue.project
rescue ActiveRecord::RecordNotFound
  render_404
end

#find_issuesObject

Find issues with a single :id param or :ids array param Raises a Unauthorized exception if one of the issues is not visible


347
348
349
350
351
352
353
354
355
# File 'app/controllers/application_controller.rb', line 347

def find_issues
  @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
  raise ActiveRecord::RecordNotFound if @issues.empty?
  raise Unauthorized unless @issues.all?(&:visible?)
  @projects = @issues.collect(&:project).compact.uniq
  @project = @projects.first if @projects.size == 1
rescue ActiveRecord::RecordNotFound
  render_404
end

#find_model_objectObject


319
320
321
322
323
324
325
326
327
# File 'app/controllers/application_controller.rb', line 319

def find_model_object
  model = self.class.model_object
  if model
    @object = model.find(params[:id])
    self.instance_variable_set('@' + controller_name.singularize, @object) if @object
  end
rescue ActiveRecord::RecordNotFound
  render_404
end

#find_optional_projectObject

Find a project based on params TODO: some subclasses override this, see about merging their logic


304
305
306
307
308
309
310
# File 'app/controllers/application_controller.rb', line 304

def find_optional_project
  @project = Project.find(params[:project_id]) unless params[:project_id].blank?
  allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
  allowed ? true : deny_access
rescue ActiveRecord::RecordNotFound
  render_404
end

#find_projectObject

Find project of id params


289
290
291
292
293
# File 'app/controllers/application_controller.rb', line 289

def find_project
  @project = Project.find(params[:id])
rescue ActiveRecord::RecordNotFound
  render_404
end

#find_project_by_project_idObject

Find project of id params


296
297
298
299
300
# File 'app/controllers/application_controller.rb', line 296

def find_project_by_project_id
  @project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
  render_404
end

#find_project_from_associationObject

Finds and sets @project based on @object.project


313
314
315
316
317
# File 'app/controllers/application_controller.rb', line 313

def find_project_from_association
  render_404 unless @object.present?

  @project = @object.project
end

#force_logout_if_password_changedObject


149
150
151
152
153
154
155
156
157
158
159
# File 'app/controllers/application_controller.rb', line 149

def force_logout_if_password_changed
  passwd_changed_on = User.current.passwd_changed_on || Time.at(0)
  # Make sure we force logout only for web browser sessions, not API calls
  # if the password was changed after the session creation.
  if session[:user_id] && passwd_changed_on.utc.to_i > session[:ctime].to_i
    reset_session
    set_localization
    flash[:error] = l(:error_session_expired)
    redirect_to 
  end
end

#handle_unverified_requestObject


43
44
45
46
47
48
49
50
51
# File 'app/controllers/application_controller.rb', line 43

def handle_unverified_request
  unless api_request?
    super
    cookies.delete(autologin_cookie_name)
    self.logged_user = nil
    set_localization
    render_error :status => 422, :message => "Invalid form authenticity token."
  end
end

#logged_user=(user) ⇒ Object

Sets the logged in user


178
179
180
181
182
183
184
185
186
# File 'app/controllers/application_controller.rb', line 178

def logged_user=(user)
  reset_session
  if user && user.is_a?(User)
    User.current = user
    start_user_session(user)
  else
    User.current = User.anonymous
  end
end

#logout_userObject

Logs out current user


189
190
191
192
193
194
195
# File 'app/controllers/application_controller.rb', line 189

def logout_user
  if User.current.logged?
    cookies.delete(autologin_cookie_name)
    Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
    self.logged_user = nil
  end
end

#missing_templateObject

Handler for ActionView::MissingTemplate exception


473
474
475
476
477
# File 'app/controllers/application_controller.rb', line 473

def missing_template
  logger.warn "Missing template, responding with 404"
  @project = nil
  render_404
end

#parse_qvalues(value) ⇒ Object

qvalues http header parser code taken from webrick


573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# File 'app/controllers/application_controller.rb', line 573

def parse_qvalues(value)
  tmp = []
  if value
    parts = value.split(/,\s*/)
    parts.each {|part|
      if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
        val = m[1]
        q = (m[2] or 1).to_f
        tmp.push([val, q])
      end
    }
    tmp = tmp.sort_by{|val, q| -q}
    tmp.collect!{|val, q| val}
  end
  return tmp
rescue
  nil
end

#per_page_optionObject

Returns the number of objects that should be displayed on the paginated list


534
535
536
537
538
539
540
541
542
543
544
545
# File 'app/controllers/application_controller.rb', line 534

def per_page_option
  per_page = nil
  if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
    per_page = params[:per_page].to_s.to_i
    session[:per_page] = per_page
  elsif session[:per_page]
    per_page = session[:per_page]
  else
    per_page = Setting.per_page_options_array.first || 25
  end
  per_page
end

#query_statement_invalid(exception) ⇒ Object

Rescues an invalid query statement. Just in caseā€¦


621
622
623
624
625
626
# File 'app/controllers/application_controller.rb', line 621

def query_statement_invalid(exception)
  logger.error "Query::StatementInvalid: #{exception.message}" if logger
  session.delete(:query)
  sort_clear if respond_to?(:sort_clear)
  render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
end

#redirect_back_or_default(default, options = {}) ⇒ Object


391
392
393
394
395
396
397
398
399
400
401
402
# File 'app/controllers/application_controller.rb', line 391

def redirect_back_or_default(default, options={})
  back_url = params[:back_url].to_s
  if back_url.present? && valid_back_url?(back_url)
    redirect_to(back_url)
    return
  elsif options[:referer]
    redirect_to_referer_or default
    return
  end
  redirect_to default
  false
end

#redirect_to_referer_or(*args, &block) ⇒ Object

Redirects to the request referer if present, redirects to args or call block otherwise.


433
434
435
436
437
438
439
440
441
442
443
# File 'app/controllers/application_controller.rb', line 433

def redirect_to_referer_or(*args, &block)
  redirect_to :back
rescue ::ActionController::RedirectBackError
  if args.any?
    redirect_to *args
  elsif block_given?
    block.call
  else
    raise "#redirect_to_referer_or takes arguments or a block"
  end
end

#render_403(options = {}) ⇒ Object


445
446
447
448
449
# File 'app/controllers/application_controller.rb', line 445

def render_403(options={})
  @project = nil
  render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
  return false
end

#render_404(options = {}) ⇒ Object


451
452
453
454
# File 'app/controllers/application_controller.rb', line 451

def render_404(options={})
  render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
  return false
end

#render_api_head(status) ⇒ Object

Renders a head API response


634
635
636
637
# File 'app/controllers/application_controller.rb', line 634

def render_api_head(status)
  # #head would return a response body with one space
  render :text => '', :status => status, :layout => nil
end

#render_api_okObject

Renders a 200 response for successfull updates or deletions via the API


629
630
631
# File 'app/controllers/application_controller.rb', line 629

def render_api_ok
  render_api_head :ok
end

#render_attachment_warning_if_needed(obj) ⇒ Object

Renders a warning flash if obj has unsaved attachments


616
617
618
# File 'app/controllers/application_controller.rb', line 616

def render_attachment_warning_if_needed(obj)
  flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
end

#render_error(arg) ⇒ Object

Renders an error response


457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'app/controllers/application_controller.rb', line 457

def render_error(arg)
  arg = {:message => arg} unless arg.is_a?(Hash)

  @message = arg[:message]
  @message = l(@message) if @message.is_a?(Symbol)
  @status = arg[:status] || 500

  respond_to do |format|
    format.html {
      render :template => 'common/error', :layout => use_layout, :status => @status
    }
    format.any { head @status }
  end
end

#render_feed(items, options = {}) ⇒ Object


499
500
501
502
503
504
505
506
# File 'app/controllers/application_controller.rb', line 499

def render_feed(items, options={})
  @items = (items || []).to_a
  @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
  @items = @items.slice(0, Setting.feeds_limit.to_i)
  @title = options[:title] || Setting.app_title
  render :template => "common/feed", :formats => [:atom], :layout => false,
         :content_type => 'application/atom+xml'
end

#render_validation_errors(objects) ⇒ Object

Renders API response on validation failure


640
641
642
643
644
645
646
647
# File 'app/controllers/application_controller.rb', line 640

def render_validation_errors(objects)
  if objects.is_a?(Array)
    @error_messages = objects.map {|object| object.errors.full_messages}.flatten
  else
    @error_messages = objects.errors.full_messages
  end
  render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
end

#require_adminObject


256
257
258
259
260
261
262
263
# File 'app/controllers/application_controller.rb', line 256

def require_admin
  return unless 
  if !User.current.admin?
    render_403
    return false
  end
  true
end

#require_admin_or_api_requestObject

Filter for actions that provide an API response but have no HTML representation for non admin users


481
482
483
484
485
486
487
488
489
490
# File 'app/controllers/application_controller.rb', line 481

def require_admin_or_api_request
  return true if api_request?
  if User.current.admin?
    true
  elsif User.current.logged?
    render_error(:status => 406)
  else
    deny_access
  end
end

#require_loginObject


230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'app/controllers/application_controller.rb', line 230

def 
  if !User.current.logged?
    # Extract only the basic url parameters on non-GET requests
    if request.get?
      url = url_for(params)
    else
      url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
    end
    respond_to do |format|
      format.html {
        if request.xhr?
          head :unauthorized
        else
          redirect_to :controller => "account", :action => "login", :back_url => url
        end
      }
      format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
      format.xml  { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
      format.js   { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
      format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
    end
    return false
  end
  true
end

#session_expirationObject


62
63
64
65
66
67
68
69
70
71
72
73
# File 'app/controllers/application_controller.rb', line 62

def session_expiration
  if session[:user_id]
    if session_expired? && !try_to_autologin
      set_localization(User.active.find_by_id(session[:user_id]))
      reset_session
      flash[:error] = l(:error_session_expired)
      redirect_to 
    else
      session[:atime] = Time.now.utc.to_i
    end
  end
end

#session_expired?Boolean

Returns:

  • (Boolean)

75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'app/controllers/application_controller.rb', line 75

def session_expired?
  if Setting.session_lifetime?
    unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
      return true
    end
  end
  if Setting.session_timeout?
    unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
      return true
    end
  end
  false
end

#set_localization(user = User.current) ⇒ Object


214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'app/controllers/application_controller.rb', line 214

def set_localization(user=User.current)
  lang = nil
  if user && user.logged?
    lang = find_language(user.language)
  end
  if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
    accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
    if !accept_lang.blank?
      accept_lang = accept_lang.downcase
      lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
    end
  end
  lang ||= Setting.default_language
  set_language_if_valid(lang)
end

#start_user_session(user) ⇒ Object


89
90
91
92
93
94
95
96
# File 'app/controllers/application_controller.rb', line 89

def start_user_session(user)
  session[:user_id] = user.id
  session[:ctime] = Time.now.utc.to_i
  session[:atime] = Time.now.utc.to_i
  if user.must_change_password?
    session[:pwd] = '1'
  end
end

#try_to_autologinObject


165
166
167
168
169
170
171
172
173
174
175
# File 'app/controllers/application_controller.rb', line 165

def try_to_autologin
  if cookies[autologin_cookie_name] && Setting.autologin?
    # auto-login feature starts a new session
    user = User.try_to_autologin(cookies[autologin_cookie_name])
    if user
      reset_session
      start_user_session(user)
    end
    user
  end
end

#use_layoutboolean, string

Picks which layout to use based on the request

Returns:

  • (boolean, string)

    name of the layout to use or false for no layout


495
496
497
# File 'app/controllers/application_controller.rb', line 495

def use_layout
  request.xhr? ? false : 'base'
end

#user_setupObject


98
99
100
101
102
103
104
# File 'app/controllers/application_controller.rb', line 98

def user_setup
  # Check the settings cache for each request
  Setting.check_cache
  # Find the current user
  User.current = find_current_user
  logger.info("  Current user: " + (User.current.logged? ? "#{User.current.} (id=#{User.current.id})" : "anonymous")) if logger
end

#verify_authenticity_tokenObject


37
38
39
40
41
# File 'app/controllers/application_controller.rb', line 37

def verify_authenticity_token
  unless api_request?
    super
  end
end