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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2013 Jean-Philippe Lang
  3. #
  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. #
  9. # 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. #
  14. # 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. require 'uri'
  18. require 'cgi'
  19. class Unauthorized < Exception; end
  20. class ApplicationController < ActionController::Base
  21. include Redmine::I18n
  22. include Redmine::Pagination
  23. include RoutesHelper
  24. helper :routes
  25. class_attribute :accept_api_auth_actions
  26. class_attribute :accept_rss_auth_actions
  27. class_attribute :model_object
  28. layout 'base'
  29. protect_from_forgery
  30. def handle_unverified_request
  31. super
  32. cookies.delete(:autologin)
  33. end
  34. before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
  35. rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
  36. rescue_from ::Unauthorized, :with => :deny_access
  37. rescue_from ::ActionView::MissingTemplate, :with => :missing_template
  38. include Redmine::Search::Controller
  39. include Redmine::MenuManager::MenuController
  40. helper Redmine::MenuManager::MenuHelper
  41. def session_expiration
  42. if session[:user_id]
  43. if session_expired? && !try_to_autologin
  44. reset_session
  45. flash[:error] = l(:error_session_expired)
  46. redirect_to signin_url
  47. else
  48. session[:atime] = Time.now.utc.to_i
  49. end
  50. end
  51. end
  52. def session_expired?
  53. if Setting.session_lifetime?
  54. unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
  55. return true
  56. end
  57. end
  58. if Setting.session_timeout?
  59. unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
  60. return true
  61. end
  62. end
  63. false
  64. end
  65. def start_user_session(user)
  66. session[:user_id] = user.id
  67. session[:ctime] = Time.now.utc.to_i
  68. session[:atime] = Time.now.utc.to_i
  69. end
  70. def user_setup
  71. # Check the settings cache for each request
  72. Setting.check_cache
  73. # Find the current user
  74. User.current = find_current_user
  75. logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
  76. end
  77. # Returns the current user or nil if no user is logged in
  78. # and starts a session if needed
  79. def find_current_user
  80. user = nil
  81. unless api_request?
  82. if session[:user_id]
  83. # existing session
  84. user = (User.active.find(session[:user_id]) rescue nil)
  85. elsif autologin_user = try_to_autologin
  86. user = autologin_user
  87. elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
  88. # RSS key authentication does not start a session
  89. user = User.find_by_rss_key(params[:key])
  90. end
  91. end
  92. if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
  93. if (key = api_key_from_request)
  94. # Use API key
  95. user = User.find_by_api_key(key)
  96. else
  97. # HTTP Basic, either username/password or API key/random
  98. authenticate_with_http_basic do |username, password|
  99. user = User.try_to_login(username, password) || User.find_by_api_key(username)
  100. end
  101. end
  102. # Switch user if requested by an admin user
  103. if user && user.admin? && (username = api_switch_user_from_request)
  104. su = User.find_by_login(username)
  105. if su && su.active?
  106. logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
  107. user = su
  108. else
  109. render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
  110. end
  111. end
  112. end
  113. user
  114. end
  115. def try_to_autologin
  116. if cookies[:autologin] && Setting.autologin?
  117. # auto-login feature starts a new session
  118. user = User.try_to_autologin(cookies[:autologin])
  119. if user
  120. reset_session
  121. start_user_session(user)
  122. end
  123. user
  124. end
  125. end
  126. # Sets the logged in user
  127. def logged_user=(user)
  128. reset_session
  129. if user && user.is_a?(User)
  130. User.current = user
  131. start_user_session(user)
  132. else
  133. User.current = User.anonymous
  134. end
  135. end
  136. # Logs out current user
  137. def logout_user
  138. if User.current.logged?
  139. cookies.delete :autologin
  140. Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
  141. self.logged_user = nil
  142. end
  143. end
  144. # check if login is globally required to access the application
  145. def check_if_login_required
  146. # no check needed if user is already logged in
  147. return true if User.current.logged?
  148. require_login if Setting.login_required?
  149. end
  150. def set_localization
  151. lang = nil
  152. if User.current.logged?
  153. lang = find_language(User.current.language)
  154. end
  155. if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
  156. accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
  157. if !accept_lang.blank?
  158. accept_lang = accept_lang.downcase
  159. lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
  160. end
  161. end
  162. lang ||= Setting.default_language
  163. set_language_if_valid(lang)
  164. end
  165. def require_login
  166. if !User.current.logged?
  167. # Extract only the basic url parameters on non-GET requests
  168. if request.get?
  169. url = url_for(params)
  170. else
  171. url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
  172. end
  173. respond_to do |format|
  174. format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
  175. format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
  176. format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  177. format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  178. format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  179. end
  180. return false
  181. end
  182. true
  183. end
  184. def require_admin
  185. return unless require_login
  186. if !User.current.admin?
  187. render_403
  188. return false
  189. end
  190. true
  191. end
  192. def deny_access
  193. User.current.logged? ? render_403 : require_login
  194. end
  195. # Authorize the user for the requested action
  196. def authorize(ctrl = params[:controller], action = params[:action], global = false)
  197. allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
  198. if allowed
  199. true
  200. else
  201. if @project && @project.archived?
  202. render_403 :message => :notice_not_authorized_archived_project
  203. else
  204. deny_access
  205. end
  206. end
  207. end
  208. # Authorize the user for the requested action outside a project
  209. def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
  210. authorize(ctrl, action, global)
  211. end
  212. # Find project of id params[:id]
  213. def find_project
  214. @project = Project.find(params[:id])
  215. rescue ActiveRecord::RecordNotFound
  216. render_404
  217. end
  218. # Find project of id params[:project_id]
  219. def find_project_by_project_id
  220. @project = Project.find(params[:project_id])
  221. rescue ActiveRecord::RecordNotFound
  222. render_404
  223. end
  224. # Find a project based on params[:project_id]
  225. # TODO: some subclasses override this, see about merging their logic
  226. def find_optional_project
  227. @project = Project.find(params[:project_id]) unless params[:project_id].blank?
  228. allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
  229. allowed ? true : deny_access
  230. rescue ActiveRecord::RecordNotFound
  231. render_404
  232. end
  233. # Finds and sets @project based on @object.project
  234. def find_project_from_association
  235. render_404 unless @object.present?
  236. @project = @object.project
  237. end
  238. def find_model_object
  239. model = self.class.model_object
  240. if model
  241. @object = model.find(params[:id])
  242. self.instance_variable_set('@' + controller_name.singularize, @object) if @object
  243. end
  244. rescue ActiveRecord::RecordNotFound
  245. render_404
  246. end
  247. def self.model_object(model)
  248. self.model_object = model
  249. end
  250. # Find the issue whose id is the :id parameter
  251. # Raises a Unauthorized exception if the issue is not visible
  252. def find_issue
  253. # Issue.visible.find(...) can not be used to redirect user to the login form
  254. # if the issue actually exists but requires authentication
  255. @issue = Issue.find(params[:id])
  256. raise Unauthorized unless @issue.visible?
  257. @project = @issue.project
  258. rescue ActiveRecord::RecordNotFound
  259. render_404
  260. end
  261. # Find issues with a single :id param or :ids array param
  262. # Raises a Unauthorized exception if one of the issues is not visible
  263. def find_issues
  264. @issues = Issue.find_all_by_id(params[:id] || params[:ids])
  265. raise ActiveRecord::RecordNotFound if @issues.empty?
  266. raise Unauthorized unless @issues.all?(&:visible?)
  267. @projects = @issues.collect(&:project).compact.uniq
  268. @project = @projects.first if @projects.size == 1
  269. rescue ActiveRecord::RecordNotFound
  270. render_404
  271. end
  272. def find_attachments
  273. if (attachments = params[:attachments]).present?
  274. att = attachments.values.collect do |attachment|
  275. Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
  276. end
  277. att.compact!
  278. end
  279. @attachments = att || []
  280. end
  281. # make sure that the user is a member of the project (or admin) if project is private
  282. # used as a before_filter for actions that do not require any particular permission on the project
  283. def check_project_privacy
  284. if @project && !@project.archived?
  285. if @project.visible?
  286. true
  287. else
  288. deny_access
  289. end
  290. else
  291. @project = nil
  292. render_404
  293. false
  294. end
  295. end
  296. def back_url
  297. url = params[:back_url]
  298. if url.nil? && referer = request.env['HTTP_REFERER']
  299. url = CGI.unescape(referer.to_s)
  300. end
  301. url
  302. end
  303. def redirect_back_or_default(default)
  304. back_url = params[:back_url].to_s
  305. if back_url.present?
  306. begin
  307. uri = URI.parse(back_url)
  308. # do not redirect user to another host or to the login or register page
  309. if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
  310. redirect_to(back_url)
  311. return
  312. end
  313. rescue URI::InvalidURIError
  314. logger.warn("Could not redirect to invalid URL #{back_url}")
  315. # redirect to default
  316. end
  317. end
  318. redirect_to default
  319. false
  320. end
  321. # Redirects to the request referer if present, redirects to args or call block otherwise.
  322. def redirect_to_referer_or(*args, &block)
  323. redirect_to :back
  324. rescue ::ActionController::RedirectBackError
  325. if args.any?
  326. redirect_to *args
  327. elsif block_given?
  328. block.call
  329. else
  330. raise "#redirect_to_referer_or takes arguments or a block"
  331. end
  332. end
  333. def render_403(options={})
  334. @project = nil
  335. render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
  336. return false
  337. end
  338. def render_404(options={})
  339. render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
  340. return false
  341. end
  342. # Renders an error response
  343. def render_error(arg)
  344. arg = {:message => arg} unless arg.is_a?(Hash)
  345. @message = arg[:message]
  346. @message = l(@message) if @message.is_a?(Symbol)
  347. @status = arg[:status] || 500
  348. respond_to do |format|
  349. format.html {
  350. render :template => 'common/error', :layout => use_layout, :status => @status
  351. }
  352. format.any { head @status }
  353. end
  354. end
  355. # Handler for ActionView::MissingTemplate exception
  356. def missing_template
  357. logger.warn "Missing template, responding with 404"
  358. @project = nil
  359. render_404
  360. end
  361. # Filter for actions that provide an API response
  362. # but have no HTML representation for non admin users
  363. def require_admin_or_api_request
  364. return true if api_request?
  365. if User.current.admin?
  366. true
  367. elsif User.current.logged?
  368. render_error(:status => 406)
  369. else
  370. deny_access
  371. end
  372. end
  373. # Picks which layout to use based on the request
  374. #
  375. # @return [boolean, string] name of the layout to use or false for no layout
  376. def use_layout
  377. request.xhr? ? false : 'base'
  378. end
  379. def invalid_authenticity_token
  380. if api_request?
  381. logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
  382. end
  383. render_error "Invalid form authenticity token."
  384. end
  385. def render_feed(items, options={})
  386. @items = items || []
  387. @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
  388. @items = @items.slice(0, Setting.feeds_limit.to_i)
  389. @title = options[:title] || Setting.app_title
  390. render :template => "common/feed", :formats => [:atom], :layout => false,
  391. :content_type => 'application/atom+xml'
  392. end
  393. def self.accept_rss_auth(*actions)
  394. if actions.any?
  395. self.accept_rss_auth_actions = actions
  396. else
  397. self.accept_rss_auth_actions || []
  398. end
  399. end
  400. def accept_rss_auth?(action=action_name)
  401. self.class.accept_rss_auth.include?(action.to_sym)
  402. end
  403. def self.accept_api_auth(*actions)
  404. if actions.any?
  405. self.accept_api_auth_actions = actions
  406. else
  407. self.accept_api_auth_actions || []
  408. end
  409. end
  410. def accept_api_auth?(action=action_name)
  411. self.class.accept_api_auth.include?(action.to_sym)
  412. end
  413. # Returns the number of objects that should be displayed
  414. # on the paginated list
  415. def per_page_option
  416. per_page = nil
  417. if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
  418. per_page = params[:per_page].to_s.to_i
  419. session[:per_page] = per_page
  420. elsif session[:per_page]
  421. per_page = session[:per_page]
  422. else
  423. per_page = Setting.per_page_options_array.first || 25
  424. end
  425. per_page
  426. end
  427. # Returns offset and limit used to retrieve objects
  428. # for an API response based on offset, limit and page parameters
  429. def api_offset_and_limit(options=params)
  430. if options[:offset].present?
  431. offset = options[:offset].to_i
  432. if offset < 0
  433. offset = 0
  434. end
  435. end
  436. limit = options[:limit].to_i
  437. if limit < 1
  438. limit = 25
  439. elsif limit > 100
  440. limit = 100
  441. end
  442. if offset.nil? && options[:page].present?
  443. offset = (options[:page].to_i - 1) * limit
  444. offset = 0 if offset < 0
  445. end
  446. offset ||= 0
  447. [offset, limit]
  448. end
  449. # qvalues http header parser
  450. # code taken from webrick
  451. def parse_qvalues(value)
  452. tmp = []
  453. if value
  454. parts = value.split(/,\s*/)
  455. parts.each {|part|
  456. if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
  457. val = m[1]
  458. q = (m[2] or 1).to_f
  459. tmp.push([val, q])
  460. end
  461. }
  462. tmp = tmp.sort_by{|val, q| -q}
  463. tmp.collect!{|val, q| val}
  464. end
  465. return tmp
  466. rescue
  467. nil
  468. end
  469. # Returns a string that can be used as filename value in Content-Disposition header
  470. def filename_for_content_disposition(name)
  471. request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
  472. end
  473. def api_request?
  474. %w(xml json).include? params[:format]
  475. end
  476. # Returns the API key present in the request
  477. def api_key_from_request
  478. if params[:key].present?
  479. params[:key].to_s
  480. elsif request.headers["X-Redmine-API-Key"].present?
  481. request.headers["X-Redmine-API-Key"].to_s
  482. end
  483. end
  484. # Returns the API 'switch user' value if present
  485. def api_switch_user_from_request
  486. request.headers["X-Redmine-Switch-User"].to_s.presence
  487. end
  488. # Renders a warning flash if obj has unsaved attachments
  489. def render_attachment_warning_if_needed(obj)
  490. flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
  491. end
  492. # Sets the `flash` notice or error based the number of issues that did not save
  493. #
  494. # @param [Array, Issue] issues all of the saved and unsaved Issues
  495. # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
  496. def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
  497. if unsaved_issue_ids.empty?
  498. flash[:notice] = l(:notice_successful_update) unless issues.empty?
  499. else
  500. flash[:error] = l(:notice_failed_to_save_issues,
  501. :count => unsaved_issue_ids.size,
  502. :total => issues.size,
  503. :ids => '#' + unsaved_issue_ids.join(', #'))
  504. end
  505. end
  506. # Rescues an invalid query statement. Just in case...
  507. def query_statement_invalid(exception)
  508. logger.error "Query::StatementInvalid: #{exception.message}" if logger
  509. session.delete(:query)
  510. sort_clear if respond_to?(:sort_clear)
  511. render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
  512. end
  513. # Renders a 200 response for successfull updates or deletions via the API
  514. def render_api_ok
  515. render_api_head :ok
  516. end
  517. # Renders a head API response
  518. def render_api_head(status)
  519. # #head would return a response body with one space
  520. render :text => '', :status => status, :layout => nil
  521. end
  522. # Renders API response on validation failure
  523. def render_validation_errors(objects)
  524. if objects.is_a?(Array)
  525. @error_messages = objects.map {|object| object.errors.full_messages}.flatten
  526. else
  527. @error_messages = objects.errors.full_messages
  528. end
  529. render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
  530. end
  531. # Overrides #_include_layout? so that #render with no arguments
  532. # doesn't use the layout for api requests
  533. def _include_layout?(*args)
  534. api_request? ? false : super
  535. end
  536. end