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