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