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