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