##// END OF EJS Templates
Merged r14560 and r14561 (#19577)....
Jean-Philippe Lang -
r14181:9d8f75d2817f
parent child
Show More
@@ -1,659 +1,677
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.any(:atom, :pdf, :csv) {
247 247 redirect_to :controller => "account", :action => "login", :back_url => url
248 248 }
249 249 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
250 250 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
251 251 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
252 252 format.any { head :unauthorized }
253 253 end
254 254 return false
255 255 end
256 256 true
257 257 end
258 258
259 259 def require_admin
260 260 return unless require_login
261 261 if !User.current.admin?
262 262 render_403
263 263 return false
264 264 end
265 265 true
266 266 end
267 267
268 268 def deny_access
269 269 User.current.logged? ? render_403 : require_login
270 270 end
271 271
272 272 # Authorize the user for the requested action
273 273 def authorize(ctrl = params[:controller], action = params[:action], global = false)
274 274 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
275 275 if allowed
276 276 true
277 277 else
278 278 if @project && @project.archived?
279 279 render_403 :message => :notice_not_authorized_archived_project
280 280 else
281 281 deny_access
282 282 end
283 283 end
284 284 end
285 285
286 286 # Authorize the user for the requested action outside a project
287 287 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
288 288 authorize(ctrl, action, global)
289 289 end
290 290
291 291 # Find project of id params[:id]
292 292 def find_project
293 293 @project = Project.find(params[:id])
294 294 rescue ActiveRecord::RecordNotFound
295 295 render_404
296 296 end
297 297
298 298 # Find project of id params[:project_id]
299 299 def find_project_by_project_id
300 300 @project = Project.find(params[:project_id])
301 301 rescue ActiveRecord::RecordNotFound
302 302 render_404
303 303 end
304 304
305 305 # Find a project based on params[:project_id]
306 306 # TODO: some subclasses override this, see about merging their logic
307 307 def find_optional_project
308 308 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
309 309 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
310 310 allowed ? true : deny_access
311 311 rescue ActiveRecord::RecordNotFound
312 312 render_404
313 313 end
314 314
315 315 # Finds and sets @project based on @object.project
316 316 def find_project_from_association
317 317 render_404 unless @object.present?
318 318
319 319 @project = @object.project
320 320 end
321 321
322 322 def find_model_object
323 323 model = self.class.model_object
324 324 if model
325 325 @object = model.find(params[:id])
326 326 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
327 327 end
328 328 rescue ActiveRecord::RecordNotFound
329 329 render_404
330 330 end
331 331
332 332 def self.model_object(model)
333 333 self.model_object = model
334 334 end
335 335
336 336 # Find the issue whose id is the :id parameter
337 337 # Raises a Unauthorized exception if the issue is not visible
338 338 def find_issue
339 339 # Issue.visible.find(...) can not be used to redirect user to the login form
340 340 # if the issue actually exists but requires authentication
341 341 @issue = Issue.find(params[:id])
342 342 raise Unauthorized unless @issue.visible?
343 343 @project = @issue.project
344 344 rescue ActiveRecord::RecordNotFound
345 345 render_404
346 346 end
347 347
348 348 # Find issues with a single :id param or :ids array param
349 349 # Raises a Unauthorized exception if one of the issues is not visible
350 350 def find_issues
351 351 @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
352 352 raise ActiveRecord::RecordNotFound if @issues.empty?
353 353 raise Unauthorized unless @issues.all?(&:visible?)
354 354 @projects = @issues.collect(&:project).compact.uniq
355 355 @project = @projects.first if @projects.size == 1
356 356 rescue ActiveRecord::RecordNotFound
357 357 render_404
358 358 end
359 359
360 360 def find_attachments
361 361 if (attachments = params[:attachments]).present?
362 362 att = attachments.values.collect do |attachment|
363 363 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
364 364 end
365 365 att.compact!
366 366 end
367 367 @attachments = att || []
368 368 end
369 369
370 370 # make sure that the user is a member of the project (or admin) if project is private
371 371 # used as a before_filter for actions that do not require any particular permission on the project
372 372 def check_project_privacy
373 373 if @project && !@project.archived?
374 374 if @project.visible?
375 375 true
376 376 else
377 377 deny_access
378 378 end
379 379 else
380 380 @project = nil
381 381 render_404
382 382 false
383 383 end
384 384 end
385 385
386 386 def back_url
387 387 url = params[:back_url]
388 388 if url.nil? && referer = request.env['HTTP_REFERER']
389 389 url = CGI.unescape(referer.to_s)
390 390 end
391 391 url
392 392 end
393 393
394 394 def redirect_back_or_default(default, options={})
395 395 back_url = params[:back_url].to_s
396 if back_url.present? && valid_back_url?(back_url)
397 redirect_to(back_url)
396 if back_url.present? && valid_url = validate_back_url(back_url)
397 redirect_to(valid_url)
398 398 return
399 399 elsif options[:referer]
400 400 redirect_to_referer_or default
401 401 return
402 402 end
403 403 redirect_to default
404 404 false
405 405 end
406 406
407 # Returns true if back_url is a valid url for redirection, otherwise false
408 def valid_back_url?(back_url)
407 # Returns a validated URL string if back_url is a valid url for redirection,
408 # otherwise false
409 def validate_back_url(back_url)
409 410 if CGI.unescape(back_url).include?('..')
410 411 return false
411 412 end
412 413
413 414 begin
414 415 uri = URI.parse(back_url)
415 416 rescue URI::InvalidURIError
416 417 return false
417 418 end
418 419
419 if uri.host.present? && uri.host != request.host
420 [:scheme, :host, :port].each do |component|
421 if uri.send(component).present? && uri.send(component) != request.send(component)
422 return false
423 end
424 uri.send(:"#{component}=", nil)
425 end
426 # Always ignore basic user:password in the URL
427 uri.userinfo = nil
428
429 path = uri.to_s
430 # Ensure that the remaining URL starts with a slash, followed by a
431 # non-slash character or the end
432 if path !~ %r{\A/([^/]|\z)}
420 433 return false
421 434 end
422 435
423 if uri.path.match(%r{/(login|account/register)})
436 if path.match(%r{/(login|account/register)})
424 437 return false
425 438 end
426 439
427 if relative_url_root.present? && !uri.path.starts_with?(relative_url_root)
440 if relative_url_root.present? && !path.starts_with?(relative_url_root)
428 441 return false
429 442 end
430 443
431 return true
444 return path
445 end
446 private :validate_back_url
447
448 def valid_back_url?(back_url)
449 !!validate_back_url(back_url)
432 450 end
433 451 private :valid_back_url?
434 452
435 453 # Redirects to the request referer if present, redirects to args or call block otherwise.
436 454 def redirect_to_referer_or(*args, &block)
437 455 redirect_to :back
438 456 rescue ::ActionController::RedirectBackError
439 457 if args.any?
440 458 redirect_to *args
441 459 elsif block_given?
442 460 block.call
443 461 else
444 462 raise "#redirect_to_referer_or takes arguments or a block"
445 463 end
446 464 end
447 465
448 466 def render_403(options={})
449 467 @project = nil
450 468 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
451 469 return false
452 470 end
453 471
454 472 def render_404(options={})
455 473 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
456 474 return false
457 475 end
458 476
459 477 # Renders an error response
460 478 def render_error(arg)
461 479 arg = {:message => arg} unless arg.is_a?(Hash)
462 480
463 481 @message = arg[:message]
464 482 @message = l(@message) if @message.is_a?(Symbol)
465 483 @status = arg[:status] || 500
466 484
467 485 respond_to do |format|
468 486 format.html {
469 487 render :template => 'common/error', :layout => use_layout, :status => @status
470 488 }
471 489 format.any { head @status }
472 490 end
473 491 end
474 492
475 493 # Handler for ActionView::MissingTemplate exception
476 494 def missing_template
477 495 logger.warn "Missing template, responding with 404"
478 496 @project = nil
479 497 render_404
480 498 end
481 499
482 500 # Filter for actions that provide an API response
483 501 # but have no HTML representation for non admin users
484 502 def require_admin_or_api_request
485 503 return true if api_request?
486 504 if User.current.admin?
487 505 true
488 506 elsif User.current.logged?
489 507 render_error(:status => 406)
490 508 else
491 509 deny_access
492 510 end
493 511 end
494 512
495 513 # Picks which layout to use based on the request
496 514 #
497 515 # @return [boolean, string] name of the layout to use or false for no layout
498 516 def use_layout
499 517 request.xhr? ? false : 'base'
500 518 end
501 519
502 520 def render_feed(items, options={})
503 521 @items = (items || []).to_a
504 522 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
505 523 @items = @items.slice(0, Setting.feeds_limit.to_i)
506 524 @title = options[:title] || Setting.app_title
507 525 render :template => "common/feed", :formats => [:atom], :layout => false,
508 526 :content_type => 'application/atom+xml'
509 527 end
510 528
511 529 def self.accept_rss_auth(*actions)
512 530 if actions.any?
513 531 self.accept_rss_auth_actions = actions
514 532 else
515 533 self.accept_rss_auth_actions || []
516 534 end
517 535 end
518 536
519 537 def accept_rss_auth?(action=action_name)
520 538 self.class.accept_rss_auth.include?(action.to_sym)
521 539 end
522 540
523 541 def self.accept_api_auth(*actions)
524 542 if actions.any?
525 543 self.accept_api_auth_actions = actions
526 544 else
527 545 self.accept_api_auth_actions || []
528 546 end
529 547 end
530 548
531 549 def accept_api_auth?(action=action_name)
532 550 self.class.accept_api_auth.include?(action.to_sym)
533 551 end
534 552
535 553 # Returns the number of objects that should be displayed
536 554 # on the paginated list
537 555 def per_page_option
538 556 per_page = nil
539 557 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
540 558 per_page = params[:per_page].to_s.to_i
541 559 session[:per_page] = per_page
542 560 elsif session[:per_page]
543 561 per_page = session[:per_page]
544 562 else
545 563 per_page = Setting.per_page_options_array.first || 25
546 564 end
547 565 per_page
548 566 end
549 567
550 568 # Returns offset and limit used to retrieve objects
551 569 # for an API response based on offset, limit and page parameters
552 570 def api_offset_and_limit(options=params)
553 571 if options[:offset].present?
554 572 offset = options[:offset].to_i
555 573 if offset < 0
556 574 offset = 0
557 575 end
558 576 end
559 577 limit = options[:limit].to_i
560 578 if limit < 1
561 579 limit = 25
562 580 elsif limit > 100
563 581 limit = 100
564 582 end
565 583 if offset.nil? && options[:page].present?
566 584 offset = (options[:page].to_i - 1) * limit
567 585 offset = 0 if offset < 0
568 586 end
569 587 offset ||= 0
570 588
571 589 [offset, limit]
572 590 end
573 591
574 592 # qvalues http header parser
575 593 # code taken from webrick
576 594 def parse_qvalues(value)
577 595 tmp = []
578 596 if value
579 597 parts = value.split(/,\s*/)
580 598 parts.each {|part|
581 599 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
582 600 val = m[1]
583 601 q = (m[2] or 1).to_f
584 602 tmp.push([val, q])
585 603 end
586 604 }
587 605 tmp = tmp.sort_by{|val, q| -q}
588 606 tmp.collect!{|val, q| val}
589 607 end
590 608 return tmp
591 609 rescue
592 610 nil
593 611 end
594 612
595 613 # Returns a string that can be used as filename value in Content-Disposition header
596 614 def filename_for_content_disposition(name)
597 615 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
598 616 end
599 617
600 618 def api_request?
601 619 %w(xml json).include? params[:format]
602 620 end
603 621
604 622 # Returns the API key present in the request
605 623 def api_key_from_request
606 624 if params[:key].present?
607 625 params[:key].to_s
608 626 elsif request.headers["X-Redmine-API-Key"].present?
609 627 request.headers["X-Redmine-API-Key"].to_s
610 628 end
611 629 end
612 630
613 631 # Returns the API 'switch user' value if present
614 632 def api_switch_user_from_request
615 633 request.headers["X-Redmine-Switch-User"].to_s.presence
616 634 end
617 635
618 636 # Renders a warning flash if obj has unsaved attachments
619 637 def render_attachment_warning_if_needed(obj)
620 638 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
621 639 end
622 640
623 641 # Rescues an invalid query statement. Just in case...
624 642 def query_statement_invalid(exception)
625 643 logger.error "Query::StatementInvalid: #{exception.message}" if logger
626 644 session.delete(:query)
627 645 sort_clear if respond_to?(:sort_clear)
628 646 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
629 647 end
630 648
631 649 # Renders a 200 response for successfull updates or deletions via the API
632 650 def render_api_ok
633 651 render_api_head :ok
634 652 end
635 653
636 654 # Renders a head API response
637 655 def render_api_head(status)
638 656 # #head would return a response body with one space
639 657 render :text => '', :status => status, :layout => nil
640 658 end
641 659
642 660 # Renders API response on validation failure
643 661 # for an object or an array of objects
644 662 def render_validation_errors(objects)
645 663 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
646 664 render_api_errors(messages)
647 665 end
648 666
649 667 def render_api_errors(*messages)
650 668 @error_messages = messages.flatten
651 669 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
652 670 end
653 671
654 672 # Overrides #_include_layout? so that #render with no arguments
655 673 # doesn't use the layout for api requests
656 674 def _include_layout?(*args)
657 675 api_request? ? false : super
658 676 end
659 677 end
@@ -1,424 +1,434
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, :email_addresses, :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 = Redmine::Utils.relative_url_root
76 77 Redmine::Utils.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 Redmine::Utils.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 = Redmine::Utils.relative_url_root
103 104 Redmine::Utils.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 Redmine::Utils.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_select_error /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_using_additional_email_address_should_send_email_to_the_address
308 318 EmailAddress.create!(:user_id => 2, :address => 'anotherAddress@foo.bar')
309 319 Token.delete_all
310 320
311 321 assert_difference 'ActionMailer::Base.deliveries.size' do
312 322 assert_difference 'Token.count' do
313 323 post :lost_password, :mail => 'ANOTHERaddress@foo.bar'
314 324 assert_redirected_to '/login'
315 325 end
316 326 end
317 327 mail = ActionMailer::Base.deliveries.last
318 328 assert_equal ['anotherAddress@foo.bar'], mail.bcc
319 329 end
320 330
321 331 def test_lost_password_for_unknown_user_should_fail
322 332 Token.delete_all
323 333 assert_no_difference 'Token.count' do
324 334 post :lost_password, :mail => 'invalid@somenet.foo'
325 335 assert_response :success
326 336 end
327 337 end
328 338
329 339 def test_lost_password_for_non_active_user_should_fail
330 340 Token.delete_all
331 341 assert User.find(2).lock!
332 342
333 343 assert_no_difference 'Token.count' do
334 344 post :lost_password, :mail => 'JSmith@somenet.foo'
335 345 assert_redirected_to '/account/lost_password'
336 346 end
337 347 end
338 348
339 349 def test_lost_password_for_user_who_cannot_change_password_should_fail
340 350 User.any_instance.stubs(:change_password_allowed?).returns(false)
341 351
342 352 assert_no_difference 'Token.count' do
343 353 post :lost_password, :mail => 'JSmith@somenet.foo'
344 354 assert_response :success
345 355 end
346 356 end
347 357
348 358 def test_get_lost_password_with_token_should_display_the_password_recovery_form
349 359 user = User.find(2)
350 360 token = Token.create!(:action => 'recovery', :user => user)
351 361
352 362 get :lost_password, :token => token.value
353 363 assert_response :success
354 364 assert_template 'password_recovery'
355 365
356 366 assert_select 'input[type=hidden][name=token][value=?]', token.value
357 367 end
358 368
359 369 def test_get_lost_password_with_invalid_token_should_redirect
360 370 get :lost_password, :token => "abcdef"
361 371 assert_redirected_to '/'
362 372 end
363 373
364 374 def test_post_lost_password_with_token_should_change_the_user_password
365 375 user = User.find(2)
366 376 token = Token.create!(:action => 'recovery', :user => user)
367 377
368 378 post :lost_password, :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
369 379 assert_redirected_to '/login'
370 380 user.reload
371 381 assert user.check_password?('newpass123')
372 382 assert_nil Token.find_by_id(token.id), "Token was not deleted"
373 383 end
374 384
375 385 def test_post_lost_password_with_token_for_non_active_user_should_fail
376 386 user = User.find(2)
377 387 token = Token.create!(:action => 'recovery', :user => user)
378 388 user.lock!
379 389
380 390 post :lost_password, :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
381 391 assert_redirected_to '/'
382 392 assert ! user.check_password?('newpass123')
383 393 end
384 394
385 395 def test_post_lost_password_with_token_and_password_confirmation_failure_should_redisplay_the_form
386 396 user = User.find(2)
387 397 token = Token.create!(:action => 'recovery', :user => user)
388 398
389 399 post :lost_password, :token => token.value, :new_password => 'newpass', :new_password_confirmation => 'wrongpass'
390 400 assert_response :success
391 401 assert_template 'password_recovery'
392 402 assert_not_nil Token.find_by_id(token.id), "Token was deleted"
393 403
394 404 assert_select 'input[type=hidden][name=token][value=?]', token.value
395 405 end
396 406
397 407 def test_post_lost_password_with_invalid_token_should_redirect
398 408 post :lost_password, :token => "abcdef", :new_password => 'newpass', :new_password_confirmation => 'newpass'
399 409 assert_redirected_to '/'
400 410 end
401 411
402 412 def test_activation_email_should_send_an_activation_email
403 413 User.find(2).update_attribute :status, User::STATUS_REGISTERED
404 414 @request.session[:registered_user_id] = 2
405 415
406 416 with_settings :self_registration => '1' do
407 417 assert_difference 'ActionMailer::Base.deliveries.size' do
408 418 get :activation_email
409 419 assert_redirected_to '/login'
410 420 end
411 421 end
412 422 end
413 423
414 424 def test_activation_email_without_session_data_should_fail
415 425 User.find(2).update_attribute :status, User::STATUS_REGISTERED
416 426
417 427 with_settings :self_registration => '1' do
418 428 assert_no_difference 'ActionMailer::Base.deliveries.size' do
419 429 get :activation_email
420 430 assert_redirected_to '/'
421 431 end
422 432 end
423 433 end
424 434 end
General Comments 0
You need to be logged in to leave comments. Login now