Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

application_controller.rb 23KB

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