"Fossies" - the Fresh Open Source Software Archive

Member "redmine-4.1.1/app/controllers/application_controller.rb" (6 Apr 2020, 20964 Bytes) of package /linux/www/redmine-4.1.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Ruby source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "application_controller.rb": 4.1.0_vs_4.1.1.

    1 # frozen_string_literal: true
    2 
    3 # Redmine - project management software
    4 # Copyright (C) 2006-2019  Jean-Philippe Lang
    5 #
    6 # This program is free software; you can redistribute it and/or
    7 # modify it under the terms of the GNU General Public License
    8 # as published by the Free Software Foundation; either version 2
    9 # of the License, or (at your option) any later version.
   10 #
   11 # This program is distributed in the hope that it will be useful,
   12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
   13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   14 # GNU General Public License for more details.
   15 #
   16 # You should have received a copy of the GNU General Public License
   17 # along with this program; if not, write to the Free Software
   18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
   19 
   20 require 'uri'
   21 require 'cgi'
   22 
   23 class Unauthorized < StandardError; end
   24 
   25 class ApplicationController < ActionController::Base
   26   include Redmine::I18n
   27   include Redmine::Pagination
   28   include Redmine::Hook::Helper
   29   include RoutesHelper
   30   include AvatarsHelper
   31 
   32   helper :routes
   33   helper :avatars
   34 
   35   class_attribute :accept_api_auth_actions
   36   class_attribute :accept_rss_auth_actions
   37   class_attribute :model_object
   38 
   39   layout 'base'
   40 
   41   protect_from_forgery
   42 
   43   def verify_authenticity_token
   44     unless api_request?
   45       super
   46     end
   47   end
   48 
   49   def handle_unverified_request
   50     unless api_request?
   51       super
   52       cookies.delete(autologin_cookie_name)
   53       self.logged_user = nil
   54       set_localization
   55       render_error :status => 422, :message => "Invalid form authenticity token."
   56     end
   57   end
   58 
   59   before_action :session_expiration, :user_setup, :check_if_login_required, :set_localization, :check_password_change
   60   after_action :record_project_usage
   61 
   62   rescue_from ::Unauthorized, :with => :deny_access
   63   rescue_from ::ActionView::MissingTemplate, :with => :missing_template
   64 
   65   include Redmine::Search::Controller
   66   include Redmine::MenuManager::MenuController
   67   helper Redmine::MenuManager::MenuHelper
   68 
   69   include Redmine::SudoMode::Controller
   70 
   71   def session_expiration
   72     if session[:user_id] && Rails.application.config.redmine_verify_sessions != false
   73       if session_expired? && !try_to_autologin
   74         set_localization(User.active.find_by_id(session[:user_id]))
   75         self.logged_user = nil
   76         flash[:error] = l(:error_session_expired)
   77         require_login
   78       end
   79     end
   80   end
   81 
   82   def session_expired?
   83     ! User.verify_session_token(session[:user_id], session[:tk])
   84   end
   85 
   86   def start_user_session(user)
   87     session[:user_id] = user.id
   88     session[:tk] = user.generate_session_token
   89     if user.must_change_password?
   90       session[:pwd] = '1'
   91     end
   92   end
   93 
   94   def user_setup
   95     # Check the settings cache for each request
   96     Setting.check_cache
   97     # Find the current user
   98     User.current = find_current_user
   99     logger.info("  Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
  100   end
  101 
  102   # Returns the current user or nil if no user is logged in
  103   # and starts a session if needed
  104   def find_current_user
  105     user = nil
  106     unless api_request?
  107       if session[:user_id]
  108         # existing session
  109         user = (User.active.find(session[:user_id]) rescue nil)
  110       elsif autologin_user = try_to_autologin
  111         user = autologin_user
  112       elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
  113         # RSS key authentication does not start a session
  114         user = User.find_by_rss_key(params[:key])
  115       end
  116     end
  117     if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
  118       if (key = api_key_from_request)
  119         # Use API key
  120         user = User.find_by_api_key(key)
  121       elsif /\ABasic /i.match?(request.authorization.to_s)
  122         # HTTP Basic, either username/password or API key/random
  123         authenticate_with_http_basic do |username, password|
  124           user = User.try_to_login(username, password) || User.find_by_api_key(username)
  125         end
  126         if user && user.must_change_password?
  127           render_error :message => 'You must change your password', :status => 403
  128           return
  129         end
  130       end
  131       # Switch user if requested by an admin user
  132       if user && user.admin? && (username = api_switch_user_from_request)
  133         su = User.find_by_login(username)
  134         if su && su.active?
  135           logger.info("  User switched by: #{user.login} (id=#{user.id})") if logger
  136           user = su
  137         else
  138           render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
  139         end
  140       end
  141     end
  142     # store current ip address in user object ephemerally
  143     user.remote_ip = request.remote_ip if user
  144     user
  145   end
  146 
  147   def autologin_cookie_name
  148     Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
  149   end
  150 
  151   def try_to_autologin
  152     if cookies[autologin_cookie_name] && Setting.autologin?
  153       # auto-login feature starts a new session
  154       user = User.try_to_autologin(cookies[autologin_cookie_name])
  155       if user
  156         reset_session
  157         start_user_session(user)
  158       end
  159       user
  160     end
  161   end
  162 
  163   # Sets the logged in user
  164   def logged_user=(user)
  165     reset_session
  166     if user && user.is_a?(User)
  167       User.current = user
  168       start_user_session(user)
  169     else
  170       User.current = User.anonymous
  171     end
  172   end
  173 
  174   # Logs out current user
  175   def logout_user
  176     if User.current.logged?
  177       if autologin = cookies.delete(autologin_cookie_name)
  178         User.current.delete_autologin_token(autologin)
  179       end
  180       User.current.delete_session_token(session[:tk])
  181       self.logged_user = nil
  182     end
  183   end
  184 
  185   # check if login is globally required to access the application
  186   def check_if_login_required
  187     # no check needed if user is already logged in
  188     return true if User.current.logged?
  189     require_login if Setting.login_required?
  190   end
  191 
  192   def check_password_change
  193     if session[:pwd]
  194       if User.current.must_change_password?
  195         flash[:error] = l(:error_password_expired)
  196         redirect_to my_password_path
  197       else
  198         session.delete(:pwd)
  199       end
  200     end
  201   end
  202 
  203   def set_localization(user=User.current)
  204     lang = nil
  205     if user && user.logged?
  206       lang = find_language(user.language)
  207     end
  208     if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
  209       accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
  210       if !accept_lang.blank?
  211         accept_lang = accept_lang.downcase
  212         lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
  213       end
  214     end
  215     lang ||= Setting.default_language
  216     set_language_if_valid(lang)
  217   end
  218 
  219   def require_login
  220     if !User.current.logged?
  221       # Extract only the basic url parameters on non-GET requests
  222       if request.get?
  223         url = request.original_url
  224       else
  225         url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
  226       end
  227       respond_to do |format|
  228         format.html {
  229           if request.xhr?
  230             head :unauthorized
  231           else
  232             redirect_to signin_path(:back_url => url)
  233           end
  234         }
  235         format.any(:atom, :pdf, :csv) {
  236           redirect_to signin_path(:back_url => url)
  237         }
  238         format.api  {
  239           if Setting.rest_api_enabled? && accept_api_auth?
  240             head(:unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"')
  241           else
  242             head(:forbidden)
  243           end
  244         }
  245         format.js   { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  246         format.any  { head :unauthorized }
  247       end
  248       return false
  249     end
  250     true
  251   end
  252 
  253   def require_admin
  254     return unless require_login
  255     if !User.current.admin?
  256       render_403
  257       return false
  258     end
  259     true
  260   end
  261 
  262   def deny_access
  263     User.current.logged? ? render_403 : require_login
  264   end
  265 
  266   # Authorize the user for the requested action
  267   def authorize(ctrl = params[:controller], action = params[:action], global = false)
  268     allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
  269     if allowed
  270       true
  271     else
  272       if @project && @project.archived?
  273         @archived_project = @project
  274         render_403 :message => :notice_not_authorized_archived_project
  275       elsif @project && !@project.allows_to?(:controller => ctrl, :action => action)
  276         # Project module is disabled
  277         render_403
  278       else
  279         deny_access
  280       end
  281     end
  282   end
  283 
  284   # Authorize the user for the requested action outside a project
  285   def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
  286     authorize(ctrl, action, global)
  287   end
  288 
  289   # Find project of id params[:id]
  290   def find_project(project_id=params[:id])
  291     @project = Project.find(project_id)
  292   rescue ActiveRecord::RecordNotFound
  293     render_404
  294   end
  295 
  296   # Find project of id params[:project_id]
  297   def find_project_by_project_id
  298     find_project(params[:project_id])
  299   end
  300 
  301   # Find project of id params[:id] if present
  302   def find_optional_project_by_id
  303     if params[:id].present?
  304       find_project(params[:id])
  305     end
  306   end
  307 
  308   # Find a project based on params[:project_id]
  309   # and authorize the user for the requested action
  310   def find_optional_project
  311     if params[:project_id].present?
  312       find_project(params[:project_id])
  313     end
  314     authorize_global
  315   end
  316 
  317   # Finds and sets @project based on @object.project
  318   def find_project_from_association
  319     render_404 unless @object.present?
  320 
  321     @project = @object.project
  322   end
  323 
  324   def find_model_object
  325     model = self.class.model_object
  326     if model
  327       @object = model.find(params[:id])
  328       self.instance_variable_set('@' + controller_name.singularize, @object) if @object
  329     end
  330   rescue ActiveRecord::RecordNotFound
  331     render_404
  332   end
  333 
  334   def self.model_object(model)
  335     self.model_object = model
  336   end
  337 
  338   # Find the issue whose id is the :id parameter
  339   # Raises a Unauthorized exception if the issue is not visible
  340   def find_issue
  341     # Issue.visible.find(...) can not be used to redirect user to the login form
  342     # if the issue actually exists but requires authentication
  343     @issue = Issue.find(params[:id])
  344     raise Unauthorized unless @issue.visible?
  345     @project = @issue.project
  346   rescue ActiveRecord::RecordNotFound
  347     render_404
  348   end
  349 
  350   # Find issues with a single :id param or :ids array param
  351   # Raises a Unauthorized exception if one of the issues is not visible
  352   def find_issues
  353     @issues = Issue.
  354       where(:id => (params[:id] || params[:ids])).
  355       preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to, {:custom_values => :custom_field}).
  356       to_a
  357     raise ActiveRecord::RecordNotFound if @issues.empty?
  358     raise Unauthorized unless @issues.all?(&:visible?)
  359     @projects = @issues.collect(&:project).compact.uniq
  360     @project = @projects.first if @projects.size == 1
  361   rescue ActiveRecord::RecordNotFound
  362     render_404
  363   end
  364 
  365   def find_attachments
  366     if (attachments = params[:attachments]).present?
  367       att = attachments.values.collect do |attachment|
  368         Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
  369       end
  370       att.compact!
  371     end
  372     @attachments = att || []
  373   end
  374 
  375   def parse_params_for_bulk_update(params)
  376     attributes = (params || {}).reject {|k,v| v.blank?}
  377     attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
  378     if custom = attributes[:custom_field_values]
  379       custom.reject! {|k,v| v.blank?}
  380       custom.keys.each do |k|
  381         if custom[k].is_a?(Array)
  382           custom[k] << '' if custom[k].delete('__none__')
  383         else
  384           custom[k] = '' if custom[k] == '__none__'
  385         end
  386       end
  387     end
  388     attributes
  389   end
  390 
  391   # make sure that the user is a member of the project (or admin) if project is private
  392   # used as a before_action for actions that do not require any particular permission on the project
  393   def check_project_privacy
  394     if @project && !@project.archived?
  395       if @project.visible?
  396         true
  397       else
  398         deny_access
  399       end
  400     else
  401       @project = nil
  402       render_404
  403       false
  404     end
  405   end
  406 
  407   def record_project_usage
  408     if @project && @project.id && User.current.logged? && User.current.allowed_to?(:view_project, @project)
  409       Redmine::ProjectJumpBox.new(User.current).project_used(@project)
  410     end
  411     true
  412   end
  413 
  414   def back_url
  415     url = params[:back_url]
  416     if url.nil? && referer = request.env['HTTP_REFERER']
  417       url = CGI.unescape(referer.to_s)
  418       # URLs that contains the utf8=[checkmark] parameter added by Rails are
  419       # parsed as invalid by URI.parse so the redirect to the back URL would
  420       # not be accepted (ApplicationController#validate_back_url would return
  421       # false)
  422       url.gsub!(/(\?|&)utf8=\u2713&?/, '\1')
  423     end
  424     url
  425   end
  426   helper_method :back_url
  427 
  428   def redirect_back_or_default(default, options={})
  429     if back_url = validate_back_url(params[:back_url].to_s)
  430       redirect_to(back_url)
  431       return
  432     elsif options[:referer]
  433       redirect_to_referer_or default
  434       return
  435     end
  436     redirect_to default
  437     false
  438   end
  439 
  440   # Returns a validated URL string if back_url is a valid url for redirection,
  441   # otherwise false
  442   def validate_back_url(back_url)
  443     return false if back_url.blank?
  444 
  445     if CGI.unescape(back_url).include?('..')
  446       return false
  447     end
  448 
  449     begin
  450       uri = URI.parse(back_url)
  451     rescue URI::InvalidURIError
  452       return false
  453     end
  454 
  455     [:scheme, :host, :port].each do |component|
  456       if uri.send(component).present? && uri.send(component) != request.send(component)
  457         return false
  458       end
  459       uri.send(:"#{component}=", nil)
  460     end
  461     # Always ignore basic user:password in the URL
  462     uri.userinfo = nil
  463 
  464     path = uri.to_s
  465     # Ensure that the remaining URL starts with a slash, followed by a
  466     # non-slash character or the end
  467     if !%r{\A/([^/]|\z)}.match?(path)
  468       return false
  469     end
  470 
  471     if %r{/(login|account/register|account/lost_password)}.match?(path)
  472       return false
  473     end
  474 
  475     if relative_url_root.present? && !path.starts_with?(relative_url_root)
  476       return false
  477     end
  478 
  479     return path
  480   end
  481   private :validate_back_url
  482   helper_method :validate_back_url
  483 
  484   def valid_back_url?(back_url)
  485     !!validate_back_url(back_url)
  486   end
  487   private :valid_back_url?
  488   helper_method :valid_back_url?
  489 
  490   # Redirects to the request referer if present, redirects to args or call block otherwise.
  491   def redirect_to_referer_or(*args, &block)
  492     if referer = request.headers["Referer"]
  493       redirect_to referer
  494     else
  495       if args.any?
  496         redirect_to *args
  497       elsif block_given?
  498         yield
  499       else
  500         raise "#redirect_to_referer_or takes arguments or a block"
  501       end
  502     end
  503   end
  504 
  505   def render_403(options={})
  506     @project = nil
  507     render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
  508     return false
  509   end
  510 
  511   def render_404(options={})
  512     render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
  513     return false
  514   end
  515 
  516   # Renders an error response
  517   def render_error(arg)
  518     arg = {:message => arg} unless arg.is_a?(Hash)
  519 
  520     @message = arg[:message]
  521     @message = l(@message) if @message.is_a?(Symbol)
  522     @status = arg[:status] || 500
  523 
  524     respond_to do |format|
  525       format.html {
  526         render :template => 'common/error', :layout => use_layout, :status => @status
  527       }
  528       format.any { head @status }
  529     end
  530   end
  531 
  532   # Handler for ActionView::MissingTemplate exception
  533   def missing_template(exception)
  534     logger.warn "Missing template, responding with 404: #{exception}"
  535     @project = nil
  536     render_404
  537   end
  538 
  539   # Filter for actions that provide an API response
  540   # but have no HTML representation for non admin users
  541   def require_admin_or_api_request
  542     return true if api_request?
  543     if User.current.admin?
  544       true
  545     elsif User.current.logged?
  546       render_error(:status => 406)
  547     else
  548       deny_access
  549     end
  550   end
  551 
  552   # Picks which layout to use based on the request
  553   #
  554   # @return [boolean, string] name of the layout to use or false for no layout
  555   def use_layout
  556     request.xhr? ? false : 'base'
  557   end
  558 
  559   def render_feed(items, options={})
  560     @items = (items || []).to_a
  561     @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
  562     @items = @items.slice(0, Setting.feeds_limit.to_i)
  563     @title = options[:title] || Setting.app_title
  564     render :template => "common/feed", :formats => [:atom], :layout => false,
  565            :content_type => 'application/atom+xml'
  566   end
  567 
  568   def self.accept_rss_auth(*actions)
  569     if actions.any?
  570       self.accept_rss_auth_actions = actions
  571     else
  572       self.accept_rss_auth_actions || []
  573     end
  574   end
  575 
  576   def accept_rss_auth?(action=action_name)
  577     self.class.accept_rss_auth.include?(action.to_sym)
  578   end
  579 
  580   def self.accept_api_auth(*actions)
  581     if actions.any?
  582       self.accept_api_auth_actions = actions
  583     else
  584       self.accept_api_auth_actions || []
  585     end
  586   end
  587 
  588   def accept_api_auth?(action=action_name)
  589     self.class.accept_api_auth.include?(action.to_sym)
  590   end
  591 
  592   # Returns the number of objects that should be displayed
  593   # on the paginated list
  594   def per_page_option
  595     per_page = nil
  596     if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
  597       per_page = params[:per_page].to_s.to_i
  598       session[:per_page] = per_page
  599     elsif session[:per_page]
  600       per_page = session[:per_page]
  601     else
  602       per_page = Setting.per_page_options_array.first || 25
  603     end
  604     per_page
  605   end
  606 
  607   # Returns offset and limit used to retrieve objects
  608   # for an API response based on offset, limit and page parameters
  609   def api_offset_and_limit(options=params)
  610     if options[:offset].present?
  611       offset = options[:offset].to_i
  612       if offset < 0
  613         offset = 0
  614       end
  615     end
  616     limit = options[:limit].to_i
  617     if limit < 1
  618       limit = 25
  619     elsif limit > 100
  620       limit = 100
  621     end
  622     if offset.nil? && options[:page].present?
  623       offset = (options[:page].to_i - 1) * limit
  624       offset = 0 if offset < 0
  625     end
  626     offset ||= 0
  627 
  628     [offset, limit]
  629   end
  630 
  631   # qvalues http header parser
  632   # code taken from webrick
  633   def parse_qvalues(value)
  634     tmp = []
  635     if value
  636       parts = value.split(/,\s*/)
  637       parts.each {|part|
  638         if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
  639           val = m[1]
  640           q = (m[2] or 1).to_f
  641           tmp.push([val, q])
  642         end
  643       }
  644       tmp = tmp.sort_by{|val, q| -q}
  645       tmp.collect!{|val, q| val}
  646     end
  647     return tmp
  648   rescue
  649     nil
  650   end
  651 
  652   # Returns a string that can be used as filename value in Content-Disposition header
  653   def filename_for_content_disposition(name)
  654     %r{(MSIE|Trident|Edge)}.match?(request.env['HTTP_USER_AGENT']) ? ERB::Util.url_encode(name) : name
  655   end
  656 
  657   def api_request?
  658     %w(xml json).include? params[:format]
  659   end
  660 
  661   # Returns the API key present in the request
  662   def api_key_from_request
  663     if params[:key].present?
  664       params[:key].to_s
  665     elsif request.headers["X-Redmine-API-Key"].present?
  666       request.headers["X-Redmine-API-Key"].to_s
  667     end
  668   end
  669 
  670   # Returns the API 'switch user' value if present
  671   def api_switch_user_from_request
  672     request.headers["X-Redmine-Switch-User"].to_s.presence
  673   end
  674 
  675   # Renders a warning flash if obj has unsaved attachments
  676   def render_attachment_warning_if_needed(obj)
  677     flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
  678   end
  679 
  680   # Rescues an invalid query statement. Just in case...
  681   def query_statement_invalid(exception)
  682     logger.error "Query::StatementInvalid: #{exception.message}" if logger
  683     session.delete(:issue_query)
  684     render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
  685   end
  686 
  687   # Renders a 204 response for successful updates or deletions via the API
  688   def render_api_ok
  689     render_api_head :no_content
  690   end
  691 
  692   # Renders a head API response
  693   def render_api_head(status)
  694     head status
  695   end
  696 
  697   # Renders API response on validation failure
  698   # for an object or an array of objects
  699   def render_validation_errors(objects)
  700     messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
  701     render_api_errors(messages)
  702   end
  703 
  704   def render_api_errors(*messages)
  705     @error_messages = messages.flatten
  706     render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
  707   end
  708 
  709   # Overrides #_include_layout? so that #render with no arguments
  710   # doesn't use the layout for api requests
  711   def _include_layout?(*args)
  712     api_request? ? false : super
  713   end
  714 end