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