##// END OF EJS Templates
Merged r14560 and r14561 (#19577)....
Jean-Philippe Lang -
r14181:9d8f75d2817f
parent child
Show More
@@ -1,659 +1,677
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 self.logged_user = nil
66 self.logged_user = nil
67 flash[:error] = l(:error_session_expired)
67 flash[:error] = l(:error_session_expired)
68 require_login
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_url = validate_back_url(back_url)
397 redirect_to(back_url)
397 redirect_to(valid_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 a validated URL string if back_url is a valid url for redirection,
408 def valid_back_url?(back_url)
408 # otherwise false
409 def validate_back_url(back_url)
409 if CGI.unescape(back_url).include?('..')
410 if CGI.unescape(back_url).include?('..')
410 return false
411 return false
411 end
412 end
412
413
413 begin
414 begin
414 uri = URI.parse(back_url)
415 uri = URI.parse(back_url)
415 rescue URI::InvalidURIError
416 rescue URI::InvalidURIError
416 return false
417 return false
417 end
418 end
418
419
419 if uri.host.present? && uri.host != request.host
420 [:scheme, :host, :port].each do |component|
421 if uri.send(component).present? && uri.send(component) != request.send(component)
422 return false
423 end
424 uri.send(:"#{component}=", nil)
425 end
426 # Always ignore basic user:password in the URL
427 uri.userinfo = nil
428
429 path = uri.to_s
430 # Ensure that the remaining URL starts with a slash, followed by a
431 # non-slash character or the end
432 if path !~ %r{\A/([^/]|\z)}
420 return false
433 return false
421 end
434 end
422
435
423 if uri.path.match(%r{/(login|account/register)})
436 if path.match(%r{/(login|account/register)})
424 return false
437 return false
425 end
438 end
426
439
427 if relative_url_root.present? && !uri.path.starts_with?(relative_url_root)
440 if relative_url_root.present? && !path.starts_with?(relative_url_root)
428 return false
441 return false
429 end
442 end
430
443
431 return true
444 return path
445 end
446 private :validate_back_url
447
448 def valid_back_url?(back_url)
449 !!validate_back_url(back_url)
432 end
450 end
433 private :valid_back_url?
451 private :valid_back_url?
434
452
435 # Redirects to the request referer if present, redirects to args or call block otherwise.
453 # Redirects to the request referer if present, redirects to args or call block otherwise.
436 def redirect_to_referer_or(*args, &block)
454 def redirect_to_referer_or(*args, &block)
437 redirect_to :back
455 redirect_to :back
438 rescue ::ActionController::RedirectBackError
456 rescue ::ActionController::RedirectBackError
439 if args.any?
457 if args.any?
440 redirect_to *args
458 redirect_to *args
441 elsif block_given?
459 elsif block_given?
442 block.call
460 block.call
443 else
461 else
444 raise "#redirect_to_referer_or takes arguments or a block"
462 raise "#redirect_to_referer_or takes arguments or a block"
445 end
463 end
446 end
464 end
447
465
448 def render_403(options={})
466 def render_403(options={})
449 @project = nil
467 @project = nil
450 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
468 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
451 return false
469 return false
452 end
470 end
453
471
454 def render_404(options={})
472 def render_404(options={})
455 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
473 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
456 return false
474 return false
457 end
475 end
458
476
459 # Renders an error response
477 # Renders an error response
460 def render_error(arg)
478 def render_error(arg)
461 arg = {:message => arg} unless arg.is_a?(Hash)
479 arg = {:message => arg} unless arg.is_a?(Hash)
462
480
463 @message = arg[:message]
481 @message = arg[:message]
464 @message = l(@message) if @message.is_a?(Symbol)
482 @message = l(@message) if @message.is_a?(Symbol)
465 @status = arg[:status] || 500
483 @status = arg[:status] || 500
466
484
467 respond_to do |format|
485 respond_to do |format|
468 format.html {
486 format.html {
469 render :template => 'common/error', :layout => use_layout, :status => @status
487 render :template => 'common/error', :layout => use_layout, :status => @status
470 }
488 }
471 format.any { head @status }
489 format.any { head @status }
472 end
490 end
473 end
491 end
474
492
475 # Handler for ActionView::MissingTemplate exception
493 # Handler for ActionView::MissingTemplate exception
476 def missing_template
494 def missing_template
477 logger.warn "Missing template, responding with 404"
495 logger.warn "Missing template, responding with 404"
478 @project = nil
496 @project = nil
479 render_404
497 render_404
480 end
498 end
481
499
482 # Filter for actions that provide an API response
500 # Filter for actions that provide an API response
483 # but have no HTML representation for non admin users
501 # but have no HTML representation for non admin users
484 def require_admin_or_api_request
502 def require_admin_or_api_request
485 return true if api_request?
503 return true if api_request?
486 if User.current.admin?
504 if User.current.admin?
487 true
505 true
488 elsif User.current.logged?
506 elsif User.current.logged?
489 render_error(:status => 406)
507 render_error(:status => 406)
490 else
508 else
491 deny_access
509 deny_access
492 end
510 end
493 end
511 end
494
512
495 # Picks which layout to use based on the request
513 # Picks which layout to use based on the request
496 #
514 #
497 # @return [boolean, string] name of the layout to use or false for no layout
515 # @return [boolean, string] name of the layout to use or false for no layout
498 def use_layout
516 def use_layout
499 request.xhr? ? false : 'base'
517 request.xhr? ? false : 'base'
500 end
518 end
501
519
502 def render_feed(items, options={})
520 def render_feed(items, options={})
503 @items = (items || []).to_a
521 @items = (items || []).to_a
504 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
522 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
505 @items = @items.slice(0, Setting.feeds_limit.to_i)
523 @items = @items.slice(0, Setting.feeds_limit.to_i)
506 @title = options[:title] || Setting.app_title
524 @title = options[:title] || Setting.app_title
507 render :template => "common/feed", :formats => [:atom], :layout => false,
525 render :template => "common/feed", :formats => [:atom], :layout => false,
508 :content_type => 'application/atom+xml'
526 :content_type => 'application/atom+xml'
509 end
527 end
510
528
511 def self.accept_rss_auth(*actions)
529 def self.accept_rss_auth(*actions)
512 if actions.any?
530 if actions.any?
513 self.accept_rss_auth_actions = actions
531 self.accept_rss_auth_actions = actions
514 else
532 else
515 self.accept_rss_auth_actions || []
533 self.accept_rss_auth_actions || []
516 end
534 end
517 end
535 end
518
536
519 def accept_rss_auth?(action=action_name)
537 def accept_rss_auth?(action=action_name)
520 self.class.accept_rss_auth.include?(action.to_sym)
538 self.class.accept_rss_auth.include?(action.to_sym)
521 end
539 end
522
540
523 def self.accept_api_auth(*actions)
541 def self.accept_api_auth(*actions)
524 if actions.any?
542 if actions.any?
525 self.accept_api_auth_actions = actions
543 self.accept_api_auth_actions = actions
526 else
544 else
527 self.accept_api_auth_actions || []
545 self.accept_api_auth_actions || []
528 end
546 end
529 end
547 end
530
548
531 def accept_api_auth?(action=action_name)
549 def accept_api_auth?(action=action_name)
532 self.class.accept_api_auth.include?(action.to_sym)
550 self.class.accept_api_auth.include?(action.to_sym)
533 end
551 end
534
552
535 # Returns the number of objects that should be displayed
553 # Returns the number of objects that should be displayed
536 # on the paginated list
554 # on the paginated list
537 def per_page_option
555 def per_page_option
538 per_page = nil
556 per_page = nil
539 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
557 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
558 per_page = params[:per_page].to_s.to_i
541 session[:per_page] = per_page
559 session[:per_page] = per_page
542 elsif session[:per_page]
560 elsif session[:per_page]
543 per_page = session[:per_page]
561 per_page = session[:per_page]
544 else
562 else
545 per_page = Setting.per_page_options_array.first || 25
563 per_page = Setting.per_page_options_array.first || 25
546 end
564 end
547 per_page
565 per_page
548 end
566 end
549
567
550 # Returns offset and limit used to retrieve objects
568 # Returns offset and limit used to retrieve objects
551 # for an API response based on offset, limit and page parameters
569 # for an API response based on offset, limit and page parameters
552 def api_offset_and_limit(options=params)
570 def api_offset_and_limit(options=params)
553 if options[:offset].present?
571 if options[:offset].present?
554 offset = options[:offset].to_i
572 offset = options[:offset].to_i
555 if offset < 0
573 if offset < 0
556 offset = 0
574 offset = 0
557 end
575 end
558 end
576 end
559 limit = options[:limit].to_i
577 limit = options[:limit].to_i
560 if limit < 1
578 if limit < 1
561 limit = 25
579 limit = 25
562 elsif limit > 100
580 elsif limit > 100
563 limit = 100
581 limit = 100
564 end
582 end
565 if offset.nil? && options[:page].present?
583 if offset.nil? && options[:page].present?
566 offset = (options[:page].to_i - 1) * limit
584 offset = (options[:page].to_i - 1) * limit
567 offset = 0 if offset < 0
585 offset = 0 if offset < 0
568 end
586 end
569 offset ||= 0
587 offset ||= 0
570
588
571 [offset, limit]
589 [offset, limit]
572 end
590 end
573
591
574 # qvalues http header parser
592 # qvalues http header parser
575 # code taken from webrick
593 # code taken from webrick
576 def parse_qvalues(value)
594 def parse_qvalues(value)
577 tmp = []
595 tmp = []
578 if value
596 if value
579 parts = value.split(/,\s*/)
597 parts = value.split(/,\s*/)
580 parts.each {|part|
598 parts.each {|part|
581 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
599 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
582 val = m[1]
600 val = m[1]
583 q = (m[2] or 1).to_f
601 q = (m[2] or 1).to_f
584 tmp.push([val, q])
602 tmp.push([val, q])
585 end
603 end
586 }
604 }
587 tmp = tmp.sort_by{|val, q| -q}
605 tmp = tmp.sort_by{|val, q| -q}
588 tmp.collect!{|val, q| val}
606 tmp.collect!{|val, q| val}
589 end
607 end
590 return tmp
608 return tmp
591 rescue
609 rescue
592 nil
610 nil
593 end
611 end
594
612
595 # Returns a string that can be used as filename value in Content-Disposition header
613 # Returns a string that can be used as filename value in Content-Disposition header
596 def filename_for_content_disposition(name)
614 def filename_for_content_disposition(name)
597 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
615 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
598 end
616 end
599
617
600 def api_request?
618 def api_request?
601 %w(xml json).include? params[:format]
619 %w(xml json).include? params[:format]
602 end
620 end
603
621
604 # Returns the API key present in the request
622 # Returns the API key present in the request
605 def api_key_from_request
623 def api_key_from_request
606 if params[:key].present?
624 if params[:key].present?
607 params[:key].to_s
625 params[:key].to_s
608 elsif request.headers["X-Redmine-API-Key"].present?
626 elsif request.headers["X-Redmine-API-Key"].present?
609 request.headers["X-Redmine-API-Key"].to_s
627 request.headers["X-Redmine-API-Key"].to_s
610 end
628 end
611 end
629 end
612
630
613 # Returns the API 'switch user' value if present
631 # Returns the API 'switch user' value if present
614 def api_switch_user_from_request
632 def api_switch_user_from_request
615 request.headers["X-Redmine-Switch-User"].to_s.presence
633 request.headers["X-Redmine-Switch-User"].to_s.presence
616 end
634 end
617
635
618 # Renders a warning flash if obj has unsaved attachments
636 # Renders a warning flash if obj has unsaved attachments
619 def render_attachment_warning_if_needed(obj)
637 def render_attachment_warning_if_needed(obj)
620 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
638 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
621 end
639 end
622
640
623 # Rescues an invalid query statement. Just in case...
641 # Rescues an invalid query statement. Just in case...
624 def query_statement_invalid(exception)
642 def query_statement_invalid(exception)
625 logger.error "Query::StatementInvalid: #{exception.message}" if logger
643 logger.error "Query::StatementInvalid: #{exception.message}" if logger
626 session.delete(:query)
644 session.delete(:query)
627 sort_clear if respond_to?(:sort_clear)
645 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."
646 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
629 end
647 end
630
648
631 # Renders a 200 response for successfull updates or deletions via the API
649 # Renders a 200 response for successfull updates or deletions via the API
632 def render_api_ok
650 def render_api_ok
633 render_api_head :ok
651 render_api_head :ok
634 end
652 end
635
653
636 # Renders a head API response
654 # Renders a head API response
637 def render_api_head(status)
655 def render_api_head(status)
638 # #head would return a response body with one space
656 # #head would return a response body with one space
639 render :text => '', :status => status, :layout => nil
657 render :text => '', :status => status, :layout => nil
640 end
658 end
641
659
642 # Renders API response on validation failure
660 # Renders API response on validation failure
643 # for an object or an array of objects
661 # for an object or an array of objects
644 def render_validation_errors(objects)
662 def render_validation_errors(objects)
645 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
663 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
646 render_api_errors(messages)
664 render_api_errors(messages)
647 end
665 end
648
666
649 def render_api_errors(*messages)
667 def render_api_errors(*messages)
650 @error_messages = messages.flatten
668 @error_messages = messages.flatten
651 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
669 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
652 end
670 end
653
671
654 # Overrides #_include_layout? so that #render with no arguments
672 # Overrides #_include_layout? so that #render with no arguments
655 # doesn't use the layout for api requests
673 # doesn't use the layout for api requests
656 def _include_layout?(*args)
674 def _include_layout?(*args)
657 api_request? ? false : super
675 api_request? ? false : super
658 end
676 end
659 end
677 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