To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / controllers / application_controller.rb @ 443:350acce374a2

History | View | Annotate | Download (15.8 KB)

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