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