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