##// END OF EJS Templates
Merged r13213 (#16530)....
Jean-Philippe Lang -
r12951:6eb875521331
parent child
Show More
@@ -1,618 +1,637
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 else
123 else
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? && request.env['HTTP_ACCEPT_LANGUAGE']
205 if lang.nil? && 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)
377 def redirect_back_or_default(default)
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 end
382 end
392 redirect_to default
383 redirect_to default
393 false
384 false
394 end
385 end
395
386
387 # Returns true if back_url is a valid url for redirection, otherwise false
388 def valid_back_url?(back_url)
389 if CGI.unescape(back_url).include?('..')
390 return false
391 end
392
393 begin
394 uri = URI.parse(back_url)
395 rescue URI::InvalidURIError
396 return false
397 end
398
399 if uri.host.present? && uri.host != request.host
400 return false
401 end
402
403 if uri.path.match(%r{/(login|account/register)})
404 return false
405 end
406
407 if relative_url_root.present? && !uri.path.starts_with?(relative_url_root)
408 return false
409 end
410
411 return true
412 end
413 private :valid_back_url?
414
396 # Redirects to the request referer if present, redirects to args or call block otherwise.
415 # Redirects to the request referer if present, redirects to args or call block otherwise.
397 def redirect_to_referer_or(*args, &block)
416 def redirect_to_referer_or(*args, &block)
398 redirect_to :back
417 redirect_to :back
399 rescue ::ActionController::RedirectBackError
418 rescue ::ActionController::RedirectBackError
400 if args.any?
419 if args.any?
401 redirect_to *args
420 redirect_to *args
402 elsif block_given?
421 elsif block_given?
403 block.call
422 block.call
404 else
423 else
405 raise "#redirect_to_referer_or takes arguments or a block"
424 raise "#redirect_to_referer_or takes arguments or a block"
406 end
425 end
407 end
426 end
408
427
409 def render_403(options={})
428 def render_403(options={})
410 @project = nil
429 @project = nil
411 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
430 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
412 return false
431 return false
413 end
432 end
414
433
415 def render_404(options={})
434 def render_404(options={})
416 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
435 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
417 return false
436 return false
418 end
437 end
419
438
420 # Renders an error response
439 # Renders an error response
421 def render_error(arg)
440 def render_error(arg)
422 arg = {:message => arg} unless arg.is_a?(Hash)
441 arg = {:message => arg} unless arg.is_a?(Hash)
423
442
424 @message = arg[:message]
443 @message = arg[:message]
425 @message = l(@message) if @message.is_a?(Symbol)
444 @message = l(@message) if @message.is_a?(Symbol)
426 @status = arg[:status] || 500
445 @status = arg[:status] || 500
427
446
428 respond_to do |format|
447 respond_to do |format|
429 format.html {
448 format.html {
430 render :template => 'common/error', :layout => use_layout, :status => @status
449 render :template => 'common/error', :layout => use_layout, :status => @status
431 }
450 }
432 format.any { head @status }
451 format.any { head @status }
433 end
452 end
434 end
453 end
435
454
436 # Handler for ActionView::MissingTemplate exception
455 # Handler for ActionView::MissingTemplate exception
437 def missing_template
456 def missing_template
438 logger.warn "Missing template, responding with 404"
457 logger.warn "Missing template, responding with 404"
439 @project = nil
458 @project = nil
440 render_404
459 render_404
441 end
460 end
442
461
443 # Filter for actions that provide an API response
462 # Filter for actions that provide an API response
444 # but have no HTML representation for non admin users
463 # but have no HTML representation for non admin users
445 def require_admin_or_api_request
464 def require_admin_or_api_request
446 return true if api_request?
465 return true if api_request?
447 if User.current.admin?
466 if User.current.admin?
448 true
467 true
449 elsif User.current.logged?
468 elsif User.current.logged?
450 render_error(:status => 406)
469 render_error(:status => 406)
451 else
470 else
452 deny_access
471 deny_access
453 end
472 end
454 end
473 end
455
474
456 # Picks which layout to use based on the request
475 # Picks which layout to use based on the request
457 #
476 #
458 # @return [boolean, string] name of the layout to use or false for no layout
477 # @return [boolean, string] name of the layout to use or false for no layout
459 def use_layout
478 def use_layout
460 request.xhr? ? false : 'base'
479 request.xhr? ? false : 'base'
461 end
480 end
462
481
463 def render_feed(items, options={})
482 def render_feed(items, options={})
464 @items = items || []
483 @items = items || []
465 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
484 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
466 @items = @items.slice(0, Setting.feeds_limit.to_i)
485 @items = @items.slice(0, Setting.feeds_limit.to_i)
467 @title = options[:title] || Setting.app_title
486 @title = options[:title] || Setting.app_title
468 render :template => "common/feed", :formats => [:atom], :layout => false,
487 render :template => "common/feed", :formats => [:atom], :layout => false,
469 :content_type => 'application/atom+xml'
488 :content_type => 'application/atom+xml'
470 end
489 end
471
490
472 def self.accept_rss_auth(*actions)
491 def self.accept_rss_auth(*actions)
473 if actions.any?
492 if actions.any?
474 self.accept_rss_auth_actions = actions
493 self.accept_rss_auth_actions = actions
475 else
494 else
476 self.accept_rss_auth_actions || []
495 self.accept_rss_auth_actions || []
477 end
496 end
478 end
497 end
479
498
480 def accept_rss_auth?(action=action_name)
499 def accept_rss_auth?(action=action_name)
481 self.class.accept_rss_auth.include?(action.to_sym)
500 self.class.accept_rss_auth.include?(action.to_sym)
482 end
501 end
483
502
484 def self.accept_api_auth(*actions)
503 def self.accept_api_auth(*actions)
485 if actions.any?
504 if actions.any?
486 self.accept_api_auth_actions = actions
505 self.accept_api_auth_actions = actions
487 else
506 else
488 self.accept_api_auth_actions || []
507 self.accept_api_auth_actions || []
489 end
508 end
490 end
509 end
491
510
492 def accept_api_auth?(action=action_name)
511 def accept_api_auth?(action=action_name)
493 self.class.accept_api_auth.include?(action.to_sym)
512 self.class.accept_api_auth.include?(action.to_sym)
494 end
513 end
495
514
496 # Returns the number of objects that should be displayed
515 # Returns the number of objects that should be displayed
497 # on the paginated list
516 # on the paginated list
498 def per_page_option
517 def per_page_option
499 per_page = nil
518 per_page = nil
500 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
519 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
501 per_page = params[:per_page].to_s.to_i
520 per_page = params[:per_page].to_s.to_i
502 session[:per_page] = per_page
521 session[:per_page] = per_page
503 elsif session[:per_page]
522 elsif session[:per_page]
504 per_page = session[:per_page]
523 per_page = session[:per_page]
505 else
524 else
506 per_page = Setting.per_page_options_array.first || 25
525 per_page = Setting.per_page_options_array.first || 25
507 end
526 end
508 per_page
527 per_page
509 end
528 end
510
529
511 # Returns offset and limit used to retrieve objects
530 # Returns offset and limit used to retrieve objects
512 # for an API response based on offset, limit and page parameters
531 # for an API response based on offset, limit and page parameters
513 def api_offset_and_limit(options=params)
532 def api_offset_and_limit(options=params)
514 if options[:offset].present?
533 if options[:offset].present?
515 offset = options[:offset].to_i
534 offset = options[:offset].to_i
516 if offset < 0
535 if offset < 0
517 offset = 0
536 offset = 0
518 end
537 end
519 end
538 end
520 limit = options[:limit].to_i
539 limit = options[:limit].to_i
521 if limit < 1
540 if limit < 1
522 limit = 25
541 limit = 25
523 elsif limit > 100
542 elsif limit > 100
524 limit = 100
543 limit = 100
525 end
544 end
526 if offset.nil? && options[:page].present?
545 if offset.nil? && options[:page].present?
527 offset = (options[:page].to_i - 1) * limit
546 offset = (options[:page].to_i - 1) * limit
528 offset = 0 if offset < 0
547 offset = 0 if offset < 0
529 end
548 end
530 offset ||= 0
549 offset ||= 0
531
550
532 [offset, limit]
551 [offset, limit]
533 end
552 end
534
553
535 # qvalues http header parser
554 # qvalues http header parser
536 # code taken from webrick
555 # code taken from webrick
537 def parse_qvalues(value)
556 def parse_qvalues(value)
538 tmp = []
557 tmp = []
539 if value
558 if value
540 parts = value.split(/,\s*/)
559 parts = value.split(/,\s*/)
541 parts.each {|part|
560 parts.each {|part|
542 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
561 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
543 val = m[1]
562 val = m[1]
544 q = (m[2] or 1).to_f
563 q = (m[2] or 1).to_f
545 tmp.push([val, q])
564 tmp.push([val, q])
546 end
565 end
547 }
566 }
548 tmp = tmp.sort_by{|val, q| -q}
567 tmp = tmp.sort_by{|val, q| -q}
549 tmp.collect!{|val, q| val}
568 tmp.collect!{|val, q| val}
550 end
569 end
551 return tmp
570 return tmp
552 rescue
571 rescue
553 nil
572 nil
554 end
573 end
555
574
556 # Returns a string that can be used as filename value in Content-Disposition header
575 # Returns a string that can be used as filename value in Content-Disposition header
557 def filename_for_content_disposition(name)
576 def filename_for_content_disposition(name)
558 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
577 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
559 end
578 end
560
579
561 def api_request?
580 def api_request?
562 %w(xml json).include? params[:format]
581 %w(xml json).include? params[:format]
563 end
582 end
564
583
565 # Returns the API key present in the request
584 # Returns the API key present in the request
566 def api_key_from_request
585 def api_key_from_request
567 if params[:key].present?
586 if params[:key].present?
568 params[:key].to_s
587 params[:key].to_s
569 elsif request.headers["X-Redmine-API-Key"].present?
588 elsif request.headers["X-Redmine-API-Key"].present?
570 request.headers["X-Redmine-API-Key"].to_s
589 request.headers["X-Redmine-API-Key"].to_s
571 end
590 end
572 end
591 end
573
592
574 # Returns the API 'switch user' value if present
593 # Returns the API 'switch user' value if present
575 def api_switch_user_from_request
594 def api_switch_user_from_request
576 request.headers["X-Redmine-Switch-User"].to_s.presence
595 request.headers["X-Redmine-Switch-User"].to_s.presence
577 end
596 end
578
597
579 # Renders a warning flash if obj has unsaved attachments
598 # Renders a warning flash if obj has unsaved attachments
580 def render_attachment_warning_if_needed(obj)
599 def render_attachment_warning_if_needed(obj)
581 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
600 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
582 end
601 end
583
602
584 # Rescues an invalid query statement. Just in case...
603 # Rescues an invalid query statement. Just in case...
585 def query_statement_invalid(exception)
604 def query_statement_invalid(exception)
586 logger.error "Query::StatementInvalid: #{exception.message}" if logger
605 logger.error "Query::StatementInvalid: #{exception.message}" if logger
587 session.delete(:query)
606 session.delete(:query)
588 sort_clear if respond_to?(:sort_clear)
607 sort_clear if respond_to?(:sort_clear)
589 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
608 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
590 end
609 end
591
610
592 # Renders a 200 response for successfull updates or deletions via the API
611 # Renders a 200 response for successfull updates or deletions via the API
593 def render_api_ok
612 def render_api_ok
594 render_api_head :ok
613 render_api_head :ok
595 end
614 end
596
615
597 # Renders a head API response
616 # Renders a head API response
598 def render_api_head(status)
617 def render_api_head(status)
599 # #head would return a response body with one space
618 # #head would return a response body with one space
600 render :text => '', :status => status, :layout => nil
619 render :text => '', :status => status, :layout => nil
601 end
620 end
602
621
603 # Renders API response on validation failure
622 # Renders API response on validation failure
604 def render_validation_errors(objects)
623 def render_validation_errors(objects)
605 if objects.is_a?(Array)
624 if objects.is_a?(Array)
606 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
625 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
607 else
626 else
608 @error_messages = objects.errors.full_messages
627 @error_messages = objects.errors.full_messages
609 end
628 end
610 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
629 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
611 end
630 end
612
631
613 # Overrides #_include_layout? so that #render with no arguments
632 # Overrides #_include_layout? so that #render with no arguments
614 # doesn't use the layout for api requests
633 # doesn't use the layout for api requests
615 def _include_layout?(*args)
634 def _include_layout?(*args)
616 api_request? ? false : super
635 api_request? ? false : super
617 end
636 end
618 end
637 end
@@ -1,356 +1,392
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_home
36 def test_get_login_while_logged_in_should_redirect_to_home
37 @request.session[:user_id] = 2
37 @request.session[:user_id] = 2
38
38
39 get :login
39 get :login
40 assert_redirected_to '/'
40 assert_redirected_to '/'
41 assert_equal 2, @request.session[:user_id]
41 assert_equal 2, @request.session[:user_id]
42 end
42 end
43
43
44 def test_login_should_redirect_to_back_url_param
44 def test_login_should_redirect_to_back_url_param
45 # request.uri is "test.host" in test environment
45 # request.uri is "test.host" in test environment
46 back_urls = [
46 back_urls = [
47 'http://test.host/issues/show/1',
47 'http://test.host/issues/show/1',
48 '/'
48 '/'
49 ]
49 ]
50 back_urls.each do |back_url|
50 back_urls.each do |back_url|
51 post :login, :username => 'jsmith', :password => 'jsmith', :back_url => back_url
51 post :login, :username => 'jsmith', :password => 'jsmith', :back_url => back_url
52 assert_redirected_to back_url
52 assert_redirected_to back_url
53 end
53 end
54 end
54 end
55
55
56 def test_login_with_suburi_should_redirect_to_back_url_param
57 @relative_url_root = ApplicationController.relative_url_root
58 ApplicationController.relative_url_root = '/redmine'
59
60 back_urls = [
61 'http://test.host/redmine/issues/show/1',
62 '/redmine'
63 ]
64 back_urls.each do |back_url|
65 post :login, :username => 'jsmith', :password => 'jsmith', :back_url => back_url
66 assert_redirected_to back_url
67 end
68 ensure
69 ApplicationController.relative_url_root = @relative_url_root
70 end
71
56 def test_login_should_not_redirect_to_another_host
72 def test_login_should_not_redirect_to_another_host
57 back_urls = [
73 back_urls = [
58 'http://test.foo/fake',
74 'http://test.foo/fake',
59 '//test.foo/fake'
75 '//test.foo/fake'
60 ]
76 ]
61 back_urls.each do |back_url|
77 back_urls.each do |back_url|
62 post :login, :username => 'jsmith', :password => 'jsmith', :back_url => back_url
78 post :login, :username => 'jsmith', :password => 'jsmith', :back_url => back_url
63 assert_redirected_to '/my/page'
79 assert_redirected_to '/my/page'
64 end
80 end
65 end
81 end
66
82
83 def test_login_with_suburi_should_not_redirect_to_another_suburi
84 @relative_url_root = ApplicationController.relative_url_root
85 ApplicationController.relative_url_root = '/redmine'
86
87 back_urls = [
88 'http://test.host/',
89 'http://test.host/fake',
90 'http://test.host/fake/issues',
91 'http://test.host/redmine/../fake',
92 'http://test.host/redmine/../fake/issues',
93 'http://test.host/redmine/%2e%2e/fake'
94 ]
95 back_urls.each do |back_url|
96 post :login, :username => 'jsmith', :password => 'jsmith', :back_url => back_url
97 assert_redirected_to '/my/page'
98 end
99 ensure
100 ApplicationController.relative_url_root = @relative_url_root
101 end
102
67 def test_login_with_wrong_password
103 def test_login_with_wrong_password
68 post :login, :username => 'admin', :password => 'bad'
104 post :login, :username => 'admin', :password => 'bad'
69 assert_response :success
105 assert_response :success
70 assert_template 'login'
106 assert_template 'login'
71
107
72 assert_select 'div.flash.error', :text => /Invalid user or password/
108 assert_select 'div.flash.error', :text => /Invalid user or password/
73 assert_select 'input[name=username][value=admin]'
109 assert_select 'input[name=username][value=admin]'
74 assert_select 'input[name=password]'
110 assert_select 'input[name=password]'
75 assert_select 'input[name=password][value]', 0
111 assert_select 'input[name=password][value]', 0
76 end
112 end
77
113
78 def test_login_with_locked_account_should_fail
114 def test_login_with_locked_account_should_fail
79 User.find(2).update_attribute :status, User::STATUS_LOCKED
115 User.find(2).update_attribute :status, User::STATUS_LOCKED
80
116
81 post :login, :username => 'jsmith', :password => 'jsmith'
117 post :login, :username => 'jsmith', :password => 'jsmith'
82 assert_redirected_to '/login'
118 assert_redirected_to '/login'
83 assert_include 'locked', flash[:error]
119 assert_include 'locked', flash[:error]
84 assert_nil @request.session[:user_id]
120 assert_nil @request.session[:user_id]
85 end
121 end
86
122
87 def test_login_as_registered_user_with_manual_activation_should_inform_user
123 def test_login_as_registered_user_with_manual_activation_should_inform_user
88 User.find(2).update_attribute :status, User::STATUS_REGISTERED
124 User.find(2).update_attribute :status, User::STATUS_REGISTERED
89
125
90 with_settings :self_registration => '2', :default_language => 'en' do
126 with_settings :self_registration => '2', :default_language => 'en' do
91 post :login, :username => 'jsmith', :password => 'jsmith'
127 post :login, :username => 'jsmith', :password => 'jsmith'
92 assert_redirected_to '/login'
128 assert_redirected_to '/login'
93 assert_include 'pending administrator approval', flash[:error]
129 assert_include 'pending administrator approval', flash[:error]
94 end
130 end
95 end
131 end
96
132
97 def test_login_as_registered_user_with_email_activation_should_propose_new_activation_email
133 def test_login_as_registered_user_with_email_activation_should_propose_new_activation_email
98 User.find(2).update_attribute :status, User::STATUS_REGISTERED
134 User.find(2).update_attribute :status, User::STATUS_REGISTERED
99
135
100 with_settings :self_registration => '1', :default_language => 'en' do
136 with_settings :self_registration => '1', :default_language => 'en' do
101 post :login, :username => 'jsmith', :password => 'jsmith'
137 post :login, :username => 'jsmith', :password => 'jsmith'
102 assert_redirected_to '/login'
138 assert_redirected_to '/login'
103 assert_equal 2, @request.session[:registered_user_id]
139 assert_equal 2, @request.session[:registered_user_id]
104 assert_include 'new activation email', flash[:error]
140 assert_include 'new activation email', flash[:error]
105 end
141 end
106 end
142 end
107
143
108 def test_login_should_rescue_auth_source_exception
144 def test_login_should_rescue_auth_source_exception
109 source = AuthSource.create!(:name => 'Test')
145 source = AuthSource.create!(:name => 'Test')
110 User.find(2).update_attribute :auth_source_id, source.id
146 User.find(2).update_attribute :auth_source_id, source.id
111 AuthSource.any_instance.stubs(:authenticate).raises(AuthSourceException.new("Something wrong"))
147 AuthSource.any_instance.stubs(:authenticate).raises(AuthSourceException.new("Something wrong"))
112
148
113 post :login, :username => 'jsmith', :password => 'jsmith'
149 post :login, :username => 'jsmith', :password => 'jsmith'
114 assert_response 500
150 assert_response 500
115 assert_error_tag :content => /Something wrong/
151 assert_error_tag :content => /Something wrong/
116 end
152 end
117
153
118 def test_login_should_reset_session
154 def test_login_should_reset_session
119 @controller.expects(:reset_session).once
155 @controller.expects(:reset_session).once
120
156
121 post :login, :username => 'jsmith', :password => 'jsmith'
157 post :login, :username => 'jsmith', :password => 'jsmith'
122 assert_response 302
158 assert_response 302
123 end
159 end
124
160
125 def test_get_logout_should_not_logout
161 def test_get_logout_should_not_logout
126 @request.session[:user_id] = 2
162 @request.session[:user_id] = 2
127 get :logout
163 get :logout
128 assert_response :success
164 assert_response :success
129 assert_template 'logout'
165 assert_template 'logout'
130
166
131 assert_equal 2, @request.session[:user_id]
167 assert_equal 2, @request.session[:user_id]
132 end
168 end
133
169
134 def test_get_logout_with_anonymous_should_redirect
170 def test_get_logout_with_anonymous_should_redirect
135 get :logout
171 get :logout
136 assert_redirected_to '/'
172 assert_redirected_to '/'
137 end
173 end
138
174
139 def test_logout
175 def test_logout
140 @request.session[:user_id] = 2
176 @request.session[:user_id] = 2
141 post :logout
177 post :logout
142 assert_redirected_to '/'
178 assert_redirected_to '/'
143 assert_nil @request.session[:user_id]
179 assert_nil @request.session[:user_id]
144 end
180 end
145
181
146 def test_logout_should_reset_session
182 def test_logout_should_reset_session
147 @controller.expects(:reset_session).once
183 @controller.expects(:reset_session).once
148
184
149 @request.session[:user_id] = 2
185 @request.session[:user_id] = 2
150 post :logout
186 post :logout
151 assert_response 302
187 assert_response 302
152 end
188 end
153
189
154 def test_get_register_with_registration_on
190 def test_get_register_with_registration_on
155 with_settings :self_registration => '3' do
191 with_settings :self_registration => '3' do
156 get :register
192 get :register
157 assert_response :success
193 assert_response :success
158 assert_template 'register'
194 assert_template 'register'
159 assert_not_nil assigns(:user)
195 assert_not_nil assigns(:user)
160
196
161 assert_select 'input[name=?]', 'user[password]'
197 assert_select 'input[name=?]', 'user[password]'
162 assert_select 'input[name=?]', 'user[password_confirmation]'
198 assert_select 'input[name=?]', 'user[password_confirmation]'
163 end
199 end
164 end
200 end
165
201
166 def test_get_register_should_detect_user_language
202 def test_get_register_should_detect_user_language
167 with_settings :self_registration => '3' do
203 with_settings :self_registration => '3' do
168 @request.env['HTTP_ACCEPT_LANGUAGE'] = 'fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3'
204 @request.env['HTTP_ACCEPT_LANGUAGE'] = 'fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3'
169 get :register
205 get :register
170 assert_response :success
206 assert_response :success
171 assert_not_nil assigns(:user)
207 assert_not_nil assigns(:user)
172 assert_equal 'fr', assigns(:user).language
208 assert_equal 'fr', assigns(:user).language
173 assert_select 'select[name=?]', 'user[language]' do
209 assert_select 'select[name=?]', 'user[language]' do
174 assert_select 'option[value=fr][selected=selected]'
210 assert_select 'option[value=fr][selected=selected]'
175 end
211 end
176 end
212 end
177 end
213 end
178
214
179 def test_get_register_with_registration_off_should_redirect
215 def test_get_register_with_registration_off_should_redirect
180 with_settings :self_registration => '0' do
216 with_settings :self_registration => '0' do
181 get :register
217 get :register
182 assert_redirected_to '/'
218 assert_redirected_to '/'
183 end
219 end
184 end
220 end
185
221
186 # See integration/account_test.rb for the full test
222 # See integration/account_test.rb for the full test
187 def test_post_register_with_registration_on
223 def test_post_register_with_registration_on
188 with_settings :self_registration => '3' do
224 with_settings :self_registration => '3' do
189 assert_difference 'User.count' do
225 assert_difference 'User.count' do
190 post :register, :user => {
226 post :register, :user => {
191 :login => 'register',
227 :login => 'register',
192 :password => 'secret123',
228 :password => 'secret123',
193 :password_confirmation => 'secret123',
229 :password_confirmation => 'secret123',
194 :firstname => 'John',
230 :firstname => 'John',
195 :lastname => 'Doe',
231 :lastname => 'Doe',
196 :mail => 'register@example.com'
232 :mail => 'register@example.com'
197 }
233 }
198 assert_redirected_to '/my/account'
234 assert_redirected_to '/my/account'
199 end
235 end
200 user = User.first(:order => 'id DESC')
236 user = User.first(:order => 'id DESC')
201 assert_equal 'register', user.login
237 assert_equal 'register', user.login
202 assert_equal 'John', user.firstname
238 assert_equal 'John', user.firstname
203 assert_equal 'Doe', user.lastname
239 assert_equal 'Doe', user.lastname
204 assert_equal 'register@example.com', user.mail
240 assert_equal 'register@example.com', user.mail
205 assert user.check_password?('secret123')
241 assert user.check_password?('secret123')
206 assert user.active?
242 assert user.active?
207 end
243 end
208 end
244 end
209
245
210 def test_post_register_with_registration_off_should_redirect
246 def test_post_register_with_registration_off_should_redirect
211 with_settings :self_registration => '0' do
247 with_settings :self_registration => '0' do
212 assert_no_difference 'User.count' do
248 assert_no_difference 'User.count' do
213 post :register, :user => {
249 post :register, :user => {
214 :login => 'register',
250 :login => 'register',
215 :password => 'test',
251 :password => 'test',
216 :password_confirmation => 'test',
252 :password_confirmation => 'test',
217 :firstname => 'John',
253 :firstname => 'John',
218 :lastname => 'Doe',
254 :lastname => 'Doe',
219 :mail => 'register@example.com'
255 :mail => 'register@example.com'
220 }
256 }
221 assert_redirected_to '/'
257 assert_redirected_to '/'
222 end
258 end
223 end
259 end
224 end
260 end
225
261
226 def test_get_lost_password_should_display_lost_password_form
262 def test_get_lost_password_should_display_lost_password_form
227 get :lost_password
263 get :lost_password
228 assert_response :success
264 assert_response :success
229 assert_select 'input[name=mail]'
265 assert_select 'input[name=mail]'
230 end
266 end
231
267
232 def test_lost_password_for_active_user_should_create_a_token
268 def test_lost_password_for_active_user_should_create_a_token
233 Token.delete_all
269 Token.delete_all
234 ActionMailer::Base.deliveries.clear
270 ActionMailer::Base.deliveries.clear
235 assert_difference 'ActionMailer::Base.deliveries.size' do
271 assert_difference 'ActionMailer::Base.deliveries.size' do
236 assert_difference 'Token.count' do
272 assert_difference 'Token.count' do
237 with_settings :host_name => 'mydomain.foo', :protocol => 'http' do
273 with_settings :host_name => 'mydomain.foo', :protocol => 'http' do
238 post :lost_password, :mail => 'JSmith@somenet.foo'
274 post :lost_password, :mail => 'JSmith@somenet.foo'
239 assert_redirected_to '/login'
275 assert_redirected_to '/login'
240 end
276 end
241 end
277 end
242 end
278 end
243
279
244 token = Token.order('id DESC').first
280 token = Token.order('id DESC').first
245 assert_equal User.find(2), token.user
281 assert_equal User.find(2), token.user
246 assert_equal 'recovery', token.action
282 assert_equal 'recovery', token.action
247
283
248 assert_select_email do
284 assert_select_email do
249 assert_select "a[href=?]", "http://mydomain.foo/account/lost_password?token=#{token.value}"
285 assert_select "a[href=?]", "http://mydomain.foo/account/lost_password?token=#{token.value}"
250 end
286 end
251 end
287 end
252
288
253 def test_lost_password_for_unknown_user_should_fail
289 def test_lost_password_for_unknown_user_should_fail
254 Token.delete_all
290 Token.delete_all
255 assert_no_difference 'Token.count' do
291 assert_no_difference 'Token.count' do
256 post :lost_password, :mail => 'invalid@somenet.foo'
292 post :lost_password, :mail => 'invalid@somenet.foo'
257 assert_response :success
293 assert_response :success
258 end
294 end
259 end
295 end
260
296
261 def test_lost_password_for_non_active_user_should_fail
297 def test_lost_password_for_non_active_user_should_fail
262 Token.delete_all
298 Token.delete_all
263 assert User.find(2).lock!
299 assert User.find(2).lock!
264
300
265 assert_no_difference 'Token.count' do
301 assert_no_difference 'Token.count' do
266 post :lost_password, :mail => 'JSmith@somenet.foo'
302 post :lost_password, :mail => 'JSmith@somenet.foo'
267 assert_redirected_to '/account/lost_password'
303 assert_redirected_to '/account/lost_password'
268 end
304 end
269 end
305 end
270
306
271 def test_lost_password_for_user_who_cannot_change_password_should_fail
307 def test_lost_password_for_user_who_cannot_change_password_should_fail
272 User.any_instance.stubs(:change_password_allowed?).returns(false)
308 User.any_instance.stubs(:change_password_allowed?).returns(false)
273
309
274 assert_no_difference 'Token.count' do
310 assert_no_difference 'Token.count' do
275 post :lost_password, :mail => 'JSmith@somenet.foo'
311 post :lost_password, :mail => 'JSmith@somenet.foo'
276 assert_response :success
312 assert_response :success
277 end
313 end
278 end
314 end
279
315
280 def test_get_lost_password_with_token_should_display_the_password_recovery_form
316 def test_get_lost_password_with_token_should_display_the_password_recovery_form
281 user = User.find(2)
317 user = User.find(2)
282 token = Token.create!(:action => 'recovery', :user => user)
318 token = Token.create!(:action => 'recovery', :user => user)
283
319
284 get :lost_password, :token => token.value
320 get :lost_password, :token => token.value
285 assert_response :success
321 assert_response :success
286 assert_template 'password_recovery'
322 assert_template 'password_recovery'
287
323
288 assert_select 'input[type=hidden][name=token][value=?]', token.value
324 assert_select 'input[type=hidden][name=token][value=?]', token.value
289 end
325 end
290
326
291 def test_get_lost_password_with_invalid_token_should_redirect
327 def test_get_lost_password_with_invalid_token_should_redirect
292 get :lost_password, :token => "abcdef"
328 get :lost_password, :token => "abcdef"
293 assert_redirected_to '/'
329 assert_redirected_to '/'
294 end
330 end
295
331
296 def test_post_lost_password_with_token_should_change_the_user_password
332 def test_post_lost_password_with_token_should_change_the_user_password
297 user = User.find(2)
333 user = User.find(2)
298 token = Token.create!(:action => 'recovery', :user => user)
334 token = Token.create!(:action => 'recovery', :user => user)
299
335
300 post :lost_password, :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
336 post :lost_password, :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
301 assert_redirected_to '/login'
337 assert_redirected_to '/login'
302 user.reload
338 user.reload
303 assert user.check_password?('newpass123')
339 assert user.check_password?('newpass123')
304 assert_nil Token.find_by_id(token.id), "Token was not deleted"
340 assert_nil Token.find_by_id(token.id), "Token was not deleted"
305 end
341 end
306
342
307 def test_post_lost_password_with_token_for_non_active_user_should_fail
343 def test_post_lost_password_with_token_for_non_active_user_should_fail
308 user = User.find(2)
344 user = User.find(2)
309 token = Token.create!(:action => 'recovery', :user => user)
345 token = Token.create!(:action => 'recovery', :user => user)
310 user.lock!
346 user.lock!
311
347
312 post :lost_password, :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
348 post :lost_password, :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
313 assert_redirected_to '/'
349 assert_redirected_to '/'
314 assert ! user.check_password?('newpass123')
350 assert ! user.check_password?('newpass123')
315 end
351 end
316
352
317 def test_post_lost_password_with_token_and_password_confirmation_failure_should_redisplay_the_form
353 def test_post_lost_password_with_token_and_password_confirmation_failure_should_redisplay_the_form
318 user = User.find(2)
354 user = User.find(2)
319 token = Token.create!(:action => 'recovery', :user => user)
355 token = Token.create!(:action => 'recovery', :user => user)
320
356
321 post :lost_password, :token => token.value, :new_password => 'newpass', :new_password_confirmation => 'wrongpass'
357 post :lost_password, :token => token.value, :new_password => 'newpass', :new_password_confirmation => 'wrongpass'
322 assert_response :success
358 assert_response :success
323 assert_template 'password_recovery'
359 assert_template 'password_recovery'
324 assert_not_nil Token.find_by_id(token.id), "Token was deleted"
360 assert_not_nil Token.find_by_id(token.id), "Token was deleted"
325
361
326 assert_select 'input[type=hidden][name=token][value=?]', token.value
362 assert_select 'input[type=hidden][name=token][value=?]', token.value
327 end
363 end
328
364
329 def test_post_lost_password_with_invalid_token_should_redirect
365 def test_post_lost_password_with_invalid_token_should_redirect
330 post :lost_password, :token => "abcdef", :new_password => 'newpass', :new_password_confirmation => 'newpass'
366 post :lost_password, :token => "abcdef", :new_password => 'newpass', :new_password_confirmation => 'newpass'
331 assert_redirected_to '/'
367 assert_redirected_to '/'
332 end
368 end
333
369
334 def test_activation_email_should_send_an_activation_email
370 def test_activation_email_should_send_an_activation_email
335 User.find(2).update_attribute :status, User::STATUS_REGISTERED
371 User.find(2).update_attribute :status, User::STATUS_REGISTERED
336 @request.session[:registered_user_id] = 2
372 @request.session[:registered_user_id] = 2
337
373
338 with_settings :self_registration => '1' do
374 with_settings :self_registration => '1' do
339 assert_difference 'ActionMailer::Base.deliveries.size' do
375 assert_difference 'ActionMailer::Base.deliveries.size' do
340 get :activation_email
376 get :activation_email
341 assert_redirected_to '/login'
377 assert_redirected_to '/login'
342 end
378 end
343 end
379 end
344 end
380 end
345
381
346 def test_activation_email_without_session_data_should_fail
382 def test_activation_email_without_session_data_should_fail
347 User.find(2).update_attribute :status, User::STATUS_REGISTERED
383 User.find(2).update_attribute :status, User::STATUS_REGISTERED
348
384
349 with_settings :self_registration => '1' do
385 with_settings :self_registration => '1' do
350 assert_no_difference 'ActionMailer::Base.deliveries.size' do
386 assert_no_difference 'ActionMailer::Base.deliveries.size' do
351 get :activation_email
387 get :activation_email
352 assert_redirected_to '/'
388 assert_redirected_to '/'
353 end
389 end
354 end
390 end
355 end
391 end
356 end
392 end
General Comments 0
You need to be logged in to leave comments. Login now