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