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