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