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