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