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