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

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