Chris@0: # redMine - project management software Chris@0: # Copyright (C) 2006-2007 Jean-Philippe Lang Chris@0: # Chris@0: # This program is free software; you can redistribute it and/or Chris@0: # modify it under the terms of the GNU General Public License Chris@0: # as published by the Free Software Foundation; either version 2 Chris@0: # of the License, or (at your option) any later version. Chris@0: # Chris@0: # This program is distributed in the hope that it will be useful, Chris@0: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@0: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@0: # GNU General Public License for more details. Chris@0: # Chris@0: # You should have received a copy of the GNU General Public License Chris@0: # along with this program; if not, write to the Free Software Chris@0: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@0: Chris@0: require 'uri' Chris@0: require 'cgi' Chris@0: Chris@0: class ApplicationController < ActionController::Base Chris@0: include Redmine::I18n Chris@0: Chris@0: layout 'base' Chris@0: exempt_from_layout 'builder' Chris@0: Chris@0: # Remove broken cookie after upgrade from 0.8.x (#4292) Chris@0: # See https://rails.lighthouseapp.com/projects/8994/tickets/3360 Chris@0: # TODO: remove it when Rails is fixed Chris@0: before_filter :delete_broken_cookies Chris@0: def delete_broken_cookies Chris@0: if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/ Chris@0: cookies.delete '_redmine_session' Chris@0: redirect_to home_path Chris@0: return false Chris@0: end Chris@0: end Chris@0: Chris@0: before_filter :user_setup, :check_if_login_required, :set_localization Chris@0: filter_parameter_logging :password Chris@0: protect_from_forgery Chris@0: Chris@0: rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token Chris@0: Chris@0: include Redmine::Search::Controller Chris@0: include Redmine::MenuManager::MenuController Chris@0: helper Redmine::MenuManager::MenuHelper Chris@0: Chris@0: Redmine::Scm::Base.all.each do |scm| Chris@0: require_dependency "repository/#{scm.underscore}" Chris@0: end Chris@0: Chris@0: def user_setup Chris@0: # Check the settings cache for each request Chris@0: Setting.check_cache Chris@0: # Find the current user Chris@0: User.current = find_current_user Chris@0: end Chris@0: Chris@0: # Returns the current user or nil if no user is logged in Chris@0: # and starts a session if needed Chris@0: def find_current_user Chris@0: if session[:user_id] Chris@0: # existing session Chris@0: (User.active.find(session[:user_id]) rescue nil) Chris@0: elsif cookies[:autologin] && Setting.autologin? Chris@0: # auto-login feature starts a new session Chris@0: user = User.try_to_autologin(cookies[:autologin]) Chris@0: session[:user_id] = user.id if user Chris@0: user Chris@0: elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action]) Chris@0: # RSS key authentication does not start a session Chris@0: User.find_by_rss_key(params[:key]) Chris@0: elsif Setting.rest_api_enabled? && ['xml', 'json'].include?(params[:format]) Chris@0: if params[:key].present? && accept_key_auth_actions.include?(params[:action]) Chris@0: # Use API key Chris@0: User.find_by_api_key(params[:key]) Chris@0: else Chris@0: # HTTP Basic, either username/password or API key/random Chris@0: authenticate_with_http_basic do |username, password| Chris@0: User.try_to_login(username, password) || User.find_by_api_key(username) Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Sets the logged in user Chris@0: def logged_user=(user) Chris@0: reset_session Chris@0: if user && user.is_a?(User) Chris@0: User.current = user Chris@0: session[:user_id] = user.id Chris@0: else Chris@0: User.current = User.anonymous Chris@0: end Chris@0: end Chris@0: Chris@0: # check if login is globally required to access the application Chris@0: def check_if_login_required Chris@0: # no check needed if user is already logged in Chris@0: return true if User.current.logged? Chris@0: require_login if Setting.login_required? Chris@0: end Chris@0: Chris@0: def set_localization Chris@0: lang = nil Chris@0: if User.current.logged? Chris@0: lang = find_language(User.current.language) Chris@0: end Chris@0: if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE'] Chris@0: accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first Chris@0: if !accept_lang.blank? Chris@0: accept_lang = accept_lang.downcase Chris@0: lang = find_language(accept_lang) || find_language(accept_lang.split('-').first) Chris@0: end Chris@0: end Chris@0: lang ||= Setting.default_language Chris@0: set_language_if_valid(lang) Chris@0: end Chris@0: Chris@0: def require_login Chris@0: if !User.current.logged? Chris@0: # Extract only the basic url parameters on non-GET requests Chris@0: if request.get? Chris@0: url = url_for(params) Chris@0: else Chris@0: url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id]) Chris@0: end Chris@0: respond_to do |format| Chris@0: format.html { redirect_to :controller => "account", :action => "login", :back_url => url } Chris@0: format.atom { redirect_to :controller => "account", :action => "login", :back_url => url } Chris@0: format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' } Chris@0: format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' } Chris@0: format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' } Chris@0: end Chris@0: return false Chris@0: end Chris@0: true Chris@0: end Chris@0: Chris@0: def require_admin Chris@0: return unless require_login Chris@0: if !User.current.admin? Chris@0: render_403 Chris@0: return false Chris@0: end Chris@0: true Chris@0: end Chris@0: Chris@0: def deny_access Chris@0: User.current.logged? ? render_403 : require_login Chris@0: end Chris@0: Chris@0: # Authorize the user for the requested action Chris@0: def authorize(ctrl = params[:controller], action = params[:action], global = false) chris@37: allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global) chris@37: if allowed chris@37: true chris@37: else chris@37: if @project && @project.archived? chris@37: render_403 :message => :notice_not_authorized_archived_project chris@37: else chris@37: deny_access chris@37: end chris@37: end Chris@0: end Chris@0: Chris@0: # Authorize the user for the requested action outside a project Chris@0: def authorize_global(ctrl = params[:controller], action = params[:action], global = true) Chris@0: authorize(ctrl, action, global) Chris@0: end Chris@0: Chris@0: # Find project of id params[:id] Chris@0: def find_project Chris@0: @project = Project.find(params[:id]) Chris@0: rescue ActiveRecord::RecordNotFound Chris@0: render_404 Chris@0: end Chris@0: chris@22: # Find project of id params[:project_id] chris@22: def find_project_by_project_id chris@22: @project = Project.find(params[:project_id]) chris@22: rescue ActiveRecord::RecordNotFound chris@22: render_404 chris@22: end chris@22: Chris@0: # Find a project based on params[:project_id] Chris@0: # TODO: some subclasses override this, see about merging their logic Chris@0: def find_optional_project Chris@0: @project = Project.find(params[:project_id]) unless params[:project_id].blank? Chris@0: allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true) Chris@0: allowed ? true : deny_access Chris@0: rescue ActiveRecord::RecordNotFound Chris@0: render_404 Chris@0: end Chris@0: Chris@0: # Finds and sets @project based on @object.project Chris@0: def find_project_from_association Chris@0: render_404 unless @object.present? Chris@0: Chris@0: @project = @object.project Chris@0: rescue ActiveRecord::RecordNotFound Chris@0: render_404 Chris@0: end Chris@0: Chris@0: def find_model_object Chris@0: model = self.class.read_inheritable_attribute('model_object') Chris@0: if model Chris@0: @object = model.find(params[:id]) Chris@0: self.instance_variable_set('@' + controller_name.singularize, @object) if @object Chris@0: end Chris@0: rescue ActiveRecord::RecordNotFound Chris@0: render_404 Chris@0: end Chris@0: Chris@0: def self.model_object(model) Chris@0: write_inheritable_attribute('model_object', model) Chris@0: end Chris@14: Chris@14: # Filter for bulk issue operations Chris@14: def find_issues Chris@14: @issues = Issue.find_all_by_id(params[:id] || params[:ids]) Chris@14: raise ActiveRecord::RecordNotFound if @issues.empty? chris@37: @projects = @issues.collect(&:project).compact.uniq chris@37: @project = @projects.first if @projects.size == 1 chris@37: rescue ActiveRecord::RecordNotFound chris@37: render_404 chris@37: end chris@37: chris@37: # Check if project is unique before bulk operations chris@37: def check_project_uniqueness chris@37: unless @project Chris@14: # TODO: let users bulk edit/move/destroy issues from different projects Chris@14: render_error 'Can not bulk edit/move/destroy issues from different projects' Chris@14: return false Chris@14: end Chris@14: end Chris@14: Chris@0: # make sure that the user is a member of the project (or admin) if project is private Chris@0: # used as a before_filter for actions that do not require any particular permission on the project Chris@0: def check_project_privacy Chris@0: if @project && @project.active? Chris@0: if @project.is_public? || User.current.member_of?(@project) || User.current.admin? Chris@0: true Chris@0: else Chris@0: User.current.logged? ? render_403 : require_login Chris@0: end Chris@0: else Chris@0: @project = nil Chris@0: render_404 Chris@0: false Chris@0: end Chris@0: end Chris@0: Chris@14: def back_url Chris@14: params[:back_url] || request.env['HTTP_REFERER'] Chris@14: end Chris@14: Chris@0: def redirect_back_or_default(default) Chris@0: back_url = CGI.unescape(params[:back_url].to_s) Chris@0: if !back_url.blank? Chris@0: begin Chris@0: uri = URI.parse(back_url) Chris@0: # do not redirect user to another host or to the login or register page Chris@0: if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)}) chris@237: # soundsoftware: if login page is https but back_url http, chris@237: # switch back_url to https to ensure cookie validity (#83) chris@237: if (uri.scheme == "http") && (URI.parse(request.url).scheme == "https") chris@237: uri.scheme = "https" chris@237: back_url = uri.to_s chris@237: end Chris@0: redirect_to(back_url) Chris@0: return Chris@0: end Chris@0: rescue URI::InvalidURIError Chris@0: # redirect to default Chris@0: end Chris@0: end Chris@0: redirect_to default Chris@0: end Chris@0: chris@37: def render_403(options={}) Chris@0: @project = nil chris@37: render_error({:message => :notice_not_authorized, :status => 403}.merge(options)) Chris@0: return false Chris@0: end Chris@0: chris@37: def render_404(options={}) chris@37: render_error({:message => :notice_file_not_found, :status => 404}.merge(options)) Chris@0: return false Chris@0: end Chris@0: chris@37: # Renders an error response chris@37: def render_error(arg) chris@37: arg = {:message => arg} unless arg.is_a?(Hash) chris@37: chris@37: @message = arg[:message] chris@37: @message = l(@message) if @message.is_a?(Symbol) chris@37: @status = arg[:status] || 500 chris@37: Chris@0: respond_to do |format| chris@37: format.html { chris@37: render :template => 'common/error', :layout => use_layout, :status => @status Chris@0: } chris@37: format.atom { head @status } chris@37: format.xml { head @status } chris@37: format.js { head @status } chris@37: format.json { head @status } Chris@0: end Chris@0: end Chris@14: Chris@14: # Picks which layout to use based on the request Chris@14: # Chris@14: # @return [boolean, string] name of the layout to use or false for no layout Chris@14: def use_layout Chris@14: request.xhr? ? false : 'base' Chris@14: end Chris@0: Chris@0: def invalid_authenticity_token Chris@0: if api_request? Chris@0: logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)." Chris@0: end Chris@79: render_error "Invalid form authenticity token. Perhaps your session has timed out; try reloading the form and entering your details again." Chris@0: end Chris@0: Chris@0: def render_feed(items, options={}) Chris@0: @items = items || [] Chris@0: @items.sort! {|x,y| y.event_datetime <=> x.event_datetime } Chris@0: @items = @items.slice(0, Setting.feeds_limit.to_i) Chris@0: @title = options[:title] || Setting.app_title Chris@0: render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml' Chris@0: end Chris@0: Chris@0: def self.accept_key_auth(*actions) Chris@0: actions = actions.flatten.map(&:to_s) Chris@0: write_inheritable_attribute('accept_key_auth_actions', actions) Chris@0: end Chris@0: Chris@0: def accept_key_auth_actions Chris@0: self.class.read_inheritable_attribute('accept_key_auth_actions') || [] Chris@0: end Chris@0: Chris@0: # Returns the number of objects that should be displayed Chris@0: # on the paginated list Chris@0: def per_page_option Chris@0: per_page = nil Chris@0: if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i) Chris@0: per_page = params[:per_page].to_s.to_i Chris@0: session[:per_page] = per_page Chris@0: elsif session[:per_page] Chris@0: per_page = session[:per_page] Chris@0: else Chris@0: per_page = Setting.per_page_options_array.first || 25 Chris@0: end Chris@0: per_page Chris@0: end Chris@0: Chris@0: # qvalues http header parser Chris@0: # code taken from webrick Chris@0: def parse_qvalues(value) Chris@0: tmp = [] Chris@0: if value Chris@0: parts = value.split(/,\s*/) Chris@0: parts.each {|part| Chris@0: if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part) Chris@0: val = m[1] Chris@0: q = (m[2] or 1).to_f Chris@0: tmp.push([val, q]) Chris@0: end Chris@0: } Chris@0: tmp = tmp.sort_by{|val, q| -q} Chris@0: tmp.collect!{|val, q| val} Chris@0: end Chris@0: return tmp Chris@0: rescue Chris@0: nil Chris@0: end Chris@0: Chris@0: # Returns a string that can be used as filename value in Content-Disposition header Chris@0: def filename_for_content_disposition(name) Chris@0: request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name Chris@0: end Chris@0: Chris@0: def api_request? Chris@0: %w(xml json).include? params[:format] Chris@0: end Chris@0: Chris@0: # Renders a warning flash if obj has unsaved attachments Chris@0: def render_attachment_warning_if_needed(obj) Chris@0: flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present? Chris@0: end Chris@0: Chris@14: # Sets the `flash` notice or error based the number of issues that did not save Chris@14: # Chris@14: # @param [Array, Issue] issues all of the saved and unsaved Issues Chris@14: # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved Chris@14: def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids) Chris@14: if unsaved_issue_ids.empty? Chris@14: flash[:notice] = l(:notice_successful_update) unless issues.empty? Chris@14: else Chris@14: flash[:error] = l(:notice_failed_to_save_issues, Chris@14: :count => unsaved_issue_ids.size, Chris@14: :total => issues.size, Chris@14: :ids => '#' + unsaved_issue_ids.join(', #')) Chris@14: end Chris@14: end Chris@14: Chris@0: # Rescues an invalid query statement. Just in case... Chris@0: def query_statement_invalid(exception) Chris@0: logger.error "Query::StatementInvalid: #{exception.message}" if logger Chris@0: session.delete(:query) Chris@0: sort_clear if respond_to?(:sort_clear) Chris@0: render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator." Chris@0: end Chris@0: Chris@0: # Converts the errors on an ActiveRecord object into a common JSON format Chris@0: def object_errors_to_json(object) Chris@0: object.errors.collect do |attribute, error| Chris@0: { attribute => error } Chris@0: end.to_json Chris@0: end Chris@0: Chris@0: end