You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

application_controller.rb 20KB

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