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