Mercurial > hg > soundsoftware-site
diff app/controllers/application_controller.rb @ 511:107d36338b70 live
Merge from branch "cannam"
author | Chris Cannam |
---|---|
date | Thu, 14 Jul 2011 10:43:07 +0100 |
parents | 851510f1b535 |
children | 7ded87cc4b80 |
line wrap: on
line diff
--- a/app/controllers/application_controller.rb Thu Jun 09 16:51:06 2011 +0100 +++ b/app/controllers/application_controller.rb Thu Jul 14 10:43:07 2011 +0100 @@ -1,16 +1,16 @@ -# redMine - project management software -# Copyright (C) 2006-2007 Jean-Philippe Lang +# Redmine - project management software +# Copyright (C) 2006-2011 Jean-Philippe Lang # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. @@ -18,34 +18,37 @@ require 'uri' require 'cgi' +class Unauthorized < Exception; end + class ApplicationController < ActionController::Base include Redmine::I18n layout 'base' - exempt_from_layout 'builder' - + exempt_from_layout 'builder', 'rsb' + # Remove broken cookie after upgrade from 0.8.x (#4292) # See https://rails.lighthouseapp.com/projects/8994/tickets/3360 # TODO: remove it when Rails is fixed before_filter :delete_broken_cookies def delete_broken_cookies if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/ - cookies.delete '_redmine_session' + cookies.delete '_redmine_session' redirect_to home_path return false end end - + before_filter :user_setup, :check_if_login_required, :set_localization filter_parameter_logging :password protect_from_forgery - + rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token - + rescue_from ::Unauthorized, :with => :deny_access + include Redmine::Search::Controller include Redmine::MenuManager::MenuController helper Redmine::MenuManager::MenuHelper - + Redmine::Scm::Base.all.each do |scm| require_dependency "repository/#{scm.underscore}" end @@ -56,7 +59,7 @@ # Find the current user User.current = find_current_user end - + # Returns the current user or nil if no user is logged in # and starts a session if needed def find_current_user @@ -68,13 +71,13 @@ user = User.try_to_autologin(cookies[:autologin]) session[:user_id] = user.id if user user - elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action]) + elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth? # RSS key authentication does not start a session User.find_by_rss_key(params[:key]) - elsif Setting.rest_api_enabled? && ['xml', 'json'].include?(params[:format]) - if params[:key].present? && accept_key_auth_actions.include?(params[:action]) + elsif Setting.rest_api_enabled? && accept_api_auth? + if (key = api_key_from_request) # Use API key - User.find_by_api_key(params[:key]) + User.find_by_api_key(key) else # HTTP Basic, either username/password or API key/random authenticate_with_http_basic do |username, password| @@ -94,14 +97,14 @@ User.current = User.anonymous end end - + # check if login is globally required to access the application def check_if_login_required # no check needed if user is already logged in return true if User.current.logged? require_login if Setting.login_required? - end - + end + def set_localization lang = nil if User.current.logged? @@ -117,7 +120,7 @@ lang ||= Setting.default_language set_language_if_valid(lang) end - + def require_login if !User.current.logged? # Extract only the basic url parameters on non-GET requests @@ -146,7 +149,7 @@ end true end - + def deny_access User.current.logged? ? render_403 : require_login end @@ -197,7 +200,7 @@ # Finds and sets @project based on @object.project def find_project_from_association render_404 unless @object.present? - + @project = @object.project rescue ActiveRecord::RecordNotFound render_404 @@ -221,12 +224,16 @@ def find_issues @issues = Issue.find_all_by_id(params[:id] || params[:ids]) raise ActiveRecord::RecordNotFound if @issues.empty? + if @issues.detect {|issue| !issue.visible?} + deny_access + return + end @projects = @issues.collect(&:project).compact.uniq @project = @projects.first if @projects.size == 1 rescue ActiveRecord::RecordNotFound render_404 end - + # Check if project is unique before bulk operations def check_project_uniqueness unless @project @@ -235,7 +242,7 @@ return false end end - + # 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 def check_project_privacy @@ -266,7 +273,11 @@ # soundsoftware: if back_url is the home page, # change it to My Page (#125) if (uri.path == home_path) - uri.path = uri.path + "/my" + if (uri.path =~ /\/$/) + uri.path = uri.path + "my" + else + uri.path = uri.path + "/my" + end end # soundsoftware: if login page is https but back_url http, # switch back_url to https to ensure cookie validity (#83) @@ -282,27 +293,28 @@ end end redirect_to default + false end - + def render_403(options={}) @project = nil render_error({:message => :notice_not_authorized, :status => 403}.merge(options)) return false end - + def render_404(options={}) render_error({:message => :notice_file_not_found, :status => 404}.merge(options)) return false end - + # Renders an error response 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 @@ -320,15 +332,15 @@ def use_layout request.xhr? ? false : 'base' end - + def invalid_authenticity_token if api_request? logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)." end render_error "Invalid form authenticity token. Perhaps your session has timed out; try reloading the form and entering your details again." end - - def render_feed(items, options={}) + + def render_feed(items, options={}) @items = items || [] @items.sort! {|x,y| y.event_datetime <=> x.event_datetime } @items = @items.slice(0, Setting.feeds_limit.to_i) @@ -336,15 +348,42 @@ render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml' end + # TODO: remove in Redmine 1.4 def self.accept_key_auth(*actions) - actions = actions.flatten.map(&:to_s) - write_inheritable_attribute('accept_key_auth_actions', actions) + ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead." + accept_rss_auth(*actions) + end + + # TODO: remove in Redmine 1.4 + def accept_key_auth_actions + ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth_actions is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead." + self.class.accept_rss_auth end - def accept_key_auth_actions - self.class.read_inheritable_attribute('accept_key_auth_actions') || [] + def self.accept_rss_auth(*actions) + if actions.any? + write_inheritable_attribute('accept_rss_auth_actions', actions) + else + read_inheritable_attribute('accept_rss_auth_actions') || [] + end end + def accept_rss_auth?(action=action_name) + self.class.accept_rss_auth.include?(action.to_sym) + end + + def self.accept_api_auth(*actions) + if actions.any? + write_inheritable_attribute('accept_api_auth_actions', actions) + else + read_inheritable_attribute('accept_api_auth_actions') || [] + end + end + + def accept_api_auth?(action=action_name) + self.class.accept_api_auth.include?(action.to_sym) + end + # Returns the number of objects that should be displayed # on the paginated list def per_page_option @@ -360,6 +399,30 @@ per_page end + # Returns offset and limit used to retrieve objects + # for an API response based on offset, limit and page parameters + 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 + # qvalues http header parser # code taken from webrick def parse_qvalues(value) @@ -380,16 +443,25 @@ rescue nil end - + # Returns a string that can be used as filename value in Content-Disposition header def filename_for_content_disposition(name) request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name end - + def api_request? %w(xml json).include? params[:format] end + # Returns the API key present in the request + def api_key_from_request + if params[:key].present? + params[:key] + elsif request.headers["X-Redmine-API-Key"].present? + request.headers["X-Redmine-API-Key"] + end + end + # Renders a warning flash if obj has unsaved attachments def render_attachment_warning_if_needed(obj) flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present? @@ -424,5 +496,37 @@ { attribute => error } end.to_json end - + + # Renders API response on validation failure + def render_validation_errors(object) + options = { :status => :unprocessable_entity, :layout => false } + options.merge!(case params[:format] + when 'xml'; { :xml => object.errors } + when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance + else + raise "Unknown format #{params[:format]} in #render_validation_errors" + end + ) + render options + end + + # Overrides #default_template so that the api template + # is used automatically if it exists + def default_template(action_name = self.action_name) + if api_request? + begin + return self.view_paths.find_template(default_template_name(action_name), 'api') + rescue ::ActionView::MissingTemplate + # the api template was not found + # fallback to the default behaviour + end + end + super + end + + # Overrides #pick_layout so that #render with no arguments + # doesn't use the layout for api requests + def pick_layout(*args) + api_request? ? nil : super + end end