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