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