##// END OF EJS Templates
Ruby1.9: enforce UTF-8 encodings on the params hash on Rails2 (#4050, #4796)...
Toshi MARUYAMA -
r8594:24d73d464465
parent child
Show More
@@ -1,526 +1,548
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2011 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
26 26 layout 'base'
27 27 exempt_from_layout 'builder', 'rsb'
28 28
29 29 protect_from_forgery
30 30 def handle_unverified_request
31 31 super
32 32 cookies.delete(:autologin)
33 33 end
34 34 # Remove broken cookie after upgrade from 0.8.x (#4292)
35 35 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
36 36 # TODO: remove it when Rails is fixed
37 37 before_filter :delete_broken_cookies
38 38 def delete_broken_cookies
39 39 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
40 40 cookies.delete '_redmine_session'
41 41 redirect_to home_path
42 42 return false
43 43 end
44 44 end
45 45
46 # FIXME: Remove this when all of Rack and Rails have learned how to
47 # properly use encodings
48 before_filter :params_filter
49
50 def params_filter
51 if RUBY_VERSION >= '1.9' && defined?(Rails) && Rails::VERSION::MAJOR < 3
52 self.utf8nize!(params)
53 end
54 end
55
56 def utf8nize!(obj)
57 if obj.is_a? String
58 obj.respond_to?(:force_encoding) ? obj.force_encoding("UTF-8") : obj
59 elsif obj.is_a? Hash
60 obj.each {|k, v| obj[k] = self.utf8nize!(v)}
61 elsif obj.is_a? Array
62 obj.each {|v| self.utf8nize!(v)}
63 else
64 obj
65 end
66 end
67
46 68 before_filter :user_setup, :check_if_login_required, :set_localization
47 69 filter_parameter_logging :password
48 70
49 71 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
50 72 rescue_from ::Unauthorized, :with => :deny_access
51 73
52 74 include Redmine::Search::Controller
53 75 include Redmine::MenuManager::MenuController
54 76 helper Redmine::MenuManager::MenuHelper
55 77
56 78 Redmine::Scm::Base.all.each do |scm|
57 79 require_dependency "repository/#{scm.underscore}"
58 80 end
59 81
60 82 def user_setup
61 83 # Check the settings cache for each request
62 84 Setting.check_cache
63 85 # Find the current user
64 86 User.current = find_current_user
65 87 end
66 88
67 89 # Returns the current user or nil if no user is logged in
68 90 # and starts a session if needed
69 91 def find_current_user
70 92 if session[:user_id]
71 93 # existing session
72 94 (User.active.find(session[:user_id]) rescue nil)
73 95 elsif cookies[:autologin] && Setting.autologin?
74 96 # auto-login feature starts a new session
75 97 user = User.try_to_autologin(cookies[:autologin])
76 98 session[:user_id] = user.id if user
77 99 user
78 100 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
79 101 # RSS key authentication does not start a session
80 102 User.find_by_rss_key(params[:key])
81 103 elsif Setting.rest_api_enabled? && accept_api_auth?
82 104 if (key = api_key_from_request)
83 105 # Use API key
84 106 User.find_by_api_key(key)
85 107 else
86 108 # HTTP Basic, either username/password or API key/random
87 109 authenticate_with_http_basic do |username, password|
88 110 User.try_to_login(username, password) || User.find_by_api_key(username)
89 111 end
90 112 end
91 113 end
92 114 end
93 115
94 116 # Sets the logged in user
95 117 def logged_user=(user)
96 118 reset_session
97 119 if user && user.is_a?(User)
98 120 User.current = user
99 121 session[:user_id] = user.id
100 122 else
101 123 User.current = User.anonymous
102 124 end
103 125 end
104 126
105 127 # check if login is globally required to access the application
106 128 def check_if_login_required
107 129 # no check needed if user is already logged in
108 130 return true if User.current.logged?
109 131 require_login if Setting.login_required?
110 132 end
111 133
112 134 def set_localization
113 135 lang = nil
114 136 if User.current.logged?
115 137 lang = find_language(User.current.language)
116 138 end
117 139 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
118 140 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
119 141 if !accept_lang.blank?
120 142 accept_lang = accept_lang.downcase
121 143 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
122 144 end
123 145 end
124 146 lang ||= Setting.default_language
125 147 set_language_if_valid(lang)
126 148 end
127 149
128 150 def require_login
129 151 if !User.current.logged?
130 152 # Extract only the basic url parameters on non-GET requests
131 153 if request.get?
132 154 url = url_for(params)
133 155 else
134 156 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
135 157 end
136 158 respond_to do |format|
137 159 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
138 160 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
139 161 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
140 162 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
141 163 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
142 164 end
143 165 return false
144 166 end
145 167 true
146 168 end
147 169
148 170 def require_admin
149 171 return unless require_login
150 172 if !User.current.admin?
151 173 render_403
152 174 return false
153 175 end
154 176 true
155 177 end
156 178
157 179 def deny_access
158 180 User.current.logged? ? render_403 : require_login
159 181 end
160 182
161 183 # Authorize the user for the requested action
162 184 def authorize(ctrl = params[:controller], action = params[:action], global = false)
163 185 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
164 186 if allowed
165 187 true
166 188 else
167 189 if @project && @project.archived?
168 190 render_403 :message => :notice_not_authorized_archived_project
169 191 else
170 192 deny_access
171 193 end
172 194 end
173 195 end
174 196
175 197 # Authorize the user for the requested action outside a project
176 198 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
177 199 authorize(ctrl, action, global)
178 200 end
179 201
180 202 # Find project of id params[:id]
181 203 def find_project
182 204 @project = Project.find(params[:id])
183 205 rescue ActiveRecord::RecordNotFound
184 206 render_404
185 207 end
186 208
187 209 # Find project of id params[:project_id]
188 210 def find_project_by_project_id
189 211 @project = Project.find(params[:project_id])
190 212 rescue ActiveRecord::RecordNotFound
191 213 render_404
192 214 end
193 215
194 216 # Find a project based on params[:project_id]
195 217 # TODO: some subclasses override this, see about merging their logic
196 218 def find_optional_project
197 219 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
198 220 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
199 221 allowed ? true : deny_access
200 222 rescue ActiveRecord::RecordNotFound
201 223 render_404
202 224 end
203 225
204 226 # Finds and sets @project based on @object.project
205 227 def find_project_from_association
206 228 render_404 unless @object.present?
207 229
208 230 @project = @object.project
209 231 end
210 232
211 233 def find_model_object
212 234 model = self.class.read_inheritable_attribute('model_object')
213 235 if model
214 236 @object = model.find(params[:id])
215 237 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
216 238 end
217 239 rescue ActiveRecord::RecordNotFound
218 240 render_404
219 241 end
220 242
221 243 def self.model_object(model)
222 244 write_inheritable_attribute('model_object', model)
223 245 end
224 246
225 247 # Filter for bulk issue operations
226 248 def find_issues
227 249 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
228 250 raise ActiveRecord::RecordNotFound if @issues.empty?
229 251 if @issues.detect {|issue| !issue.visible?}
230 252 deny_access
231 253 return
232 254 end
233 255 @projects = @issues.collect(&:project).compact.uniq
234 256 @project = @projects.first if @projects.size == 1
235 257 rescue ActiveRecord::RecordNotFound
236 258 render_404
237 259 end
238 260
239 261 # Check if project is unique before bulk operations
240 262 def check_project_uniqueness
241 263 unless @project
242 264 # TODO: let users bulk edit/move/destroy issues from different projects
243 265 render_error 'Can not bulk edit/move/destroy issues from different projects'
244 266 return false
245 267 end
246 268 end
247 269
248 270 # make sure that the user is a member of the project (or admin) if project is private
249 271 # used as a before_filter for actions that do not require any particular permission on the project
250 272 def check_project_privacy
251 273 if @project && @project.active?
252 274 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
253 275 true
254 276 else
255 277 deny_access
256 278 end
257 279 else
258 280 @project = nil
259 281 render_404
260 282 false
261 283 end
262 284 end
263 285
264 286 def back_url
265 287 params[:back_url] || request.env['HTTP_REFERER']
266 288 end
267 289
268 290 def redirect_back_or_default(default)
269 291 back_url = CGI.unescape(params[:back_url].to_s)
270 292 if !back_url.blank?
271 293 begin
272 294 uri = URI.parse(back_url)
273 295 # do not redirect user to another host or to the login or register page
274 296 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
275 297 redirect_to(back_url)
276 298 return
277 299 end
278 300 rescue URI::InvalidURIError
279 301 # redirect to default
280 302 end
281 303 end
282 304 redirect_to default
283 305 false
284 306 end
285 307
286 308 def render_403(options={})
287 309 @project = nil
288 310 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
289 311 return false
290 312 end
291 313
292 314 def render_404(options={})
293 315 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
294 316 return false
295 317 end
296 318
297 319 # Renders an error response
298 320 def render_error(arg)
299 321 arg = {:message => arg} unless arg.is_a?(Hash)
300 322
301 323 @message = arg[:message]
302 324 @message = l(@message) if @message.is_a?(Symbol)
303 325 @status = arg[:status] || 500
304 326
305 327 respond_to do |format|
306 328 format.html {
307 329 render :template => 'common/error', :layout => use_layout, :status => @status
308 330 }
309 331 format.atom { head @status }
310 332 format.xml { head @status }
311 333 format.js { head @status }
312 334 format.json { head @status }
313 335 end
314 336 end
315 337
316 338 # Filter for actions that provide an API response
317 339 # but have no HTML representation for non admin users
318 340 def require_admin_or_api_request
319 341 return true if api_request?
320 342 if User.current.admin?
321 343 true
322 344 elsif User.current.logged?
323 345 render_error(:status => 406)
324 346 else
325 347 deny_access
326 348 end
327 349 end
328 350
329 351 # Picks which layout to use based on the request
330 352 #
331 353 # @return [boolean, string] name of the layout to use or false for no layout
332 354 def use_layout
333 355 request.xhr? ? false : 'base'
334 356 end
335 357
336 358 def invalid_authenticity_token
337 359 if api_request?
338 360 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
339 361 end
340 362 render_error "Invalid form authenticity token."
341 363 end
342 364
343 365 def render_feed(items, options={})
344 366 @items = items || []
345 367 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
346 368 @items = @items.slice(0, Setting.feeds_limit.to_i)
347 369 @title = options[:title] || Setting.app_title
348 370 render :template => "common/feed.atom", :layout => false,
349 371 :content_type => 'application/atom+xml'
350 372 end
351 373
352 374 # TODO: remove in Redmine 1.4
353 375 def self.accept_key_auth(*actions)
354 376 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
355 377 accept_rss_auth(*actions)
356 378 end
357 379
358 380 # TODO: remove in Redmine 1.4
359 381 def accept_key_auth_actions
360 382 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth_actions is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
361 383 self.class.accept_rss_auth
362 384 end
363 385
364 386 def self.accept_rss_auth(*actions)
365 387 if actions.any?
366 388 write_inheritable_attribute('accept_rss_auth_actions', actions)
367 389 else
368 390 read_inheritable_attribute('accept_rss_auth_actions') || []
369 391 end
370 392 end
371 393
372 394 def accept_rss_auth?(action=action_name)
373 395 self.class.accept_rss_auth.include?(action.to_sym)
374 396 end
375 397
376 398 def self.accept_api_auth(*actions)
377 399 if actions.any?
378 400 write_inheritable_attribute('accept_api_auth_actions', actions)
379 401 else
380 402 read_inheritable_attribute('accept_api_auth_actions') || []
381 403 end
382 404 end
383 405
384 406 def accept_api_auth?(action=action_name)
385 407 self.class.accept_api_auth.include?(action.to_sym)
386 408 end
387 409
388 410 # Returns the number of objects that should be displayed
389 411 # on the paginated list
390 412 def per_page_option
391 413 per_page = nil
392 414 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
393 415 per_page = params[:per_page].to_s.to_i
394 416 session[:per_page] = per_page
395 417 elsif session[:per_page]
396 418 per_page = session[:per_page]
397 419 else
398 420 per_page = Setting.per_page_options_array.first || 25
399 421 end
400 422 per_page
401 423 end
402 424
403 425 # Returns offset and limit used to retrieve objects
404 426 # for an API response based on offset, limit and page parameters
405 427 def api_offset_and_limit(options=params)
406 428 if options[:offset].present?
407 429 offset = options[:offset].to_i
408 430 if offset < 0
409 431 offset = 0
410 432 end
411 433 end
412 434 limit = options[:limit].to_i
413 435 if limit < 1
414 436 limit = 25
415 437 elsif limit > 100
416 438 limit = 100
417 439 end
418 440 if offset.nil? && options[:page].present?
419 441 offset = (options[:page].to_i - 1) * limit
420 442 offset = 0 if offset < 0
421 443 end
422 444 offset ||= 0
423 445
424 446 [offset, limit]
425 447 end
426 448
427 449 # qvalues http header parser
428 450 # code taken from webrick
429 451 def parse_qvalues(value)
430 452 tmp = []
431 453 if value
432 454 parts = value.split(/,\s*/)
433 455 parts.each {|part|
434 456 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
435 457 val = m[1]
436 458 q = (m[2] or 1).to_f
437 459 tmp.push([val, q])
438 460 end
439 461 }
440 462 tmp = tmp.sort_by{|val, q| -q}
441 463 tmp.collect!{|val, q| val}
442 464 end
443 465 return tmp
444 466 rescue
445 467 nil
446 468 end
447 469
448 470 # Returns a string that can be used as filename value in Content-Disposition header
449 471 def filename_for_content_disposition(name)
450 472 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
451 473 end
452 474
453 475 def api_request?
454 476 %w(xml json).include? params[:format]
455 477 end
456 478
457 479 # Returns the API key present in the request
458 480 def api_key_from_request
459 481 if params[:key].present?
460 482 params[:key]
461 483 elsif request.headers["X-Redmine-API-Key"].present?
462 484 request.headers["X-Redmine-API-Key"]
463 485 end
464 486 end
465 487
466 488 # Renders a warning flash if obj has unsaved attachments
467 489 def render_attachment_warning_if_needed(obj)
468 490 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
469 491 end
470 492
471 493 # Sets the `flash` notice or error based the number of issues that did not save
472 494 #
473 495 # @param [Array, Issue] issues all of the saved and unsaved Issues
474 496 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
475 497 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
476 498 if unsaved_issue_ids.empty?
477 499 flash[:notice] = l(:notice_successful_update) unless issues.empty?
478 500 else
479 501 flash[:error] = l(:notice_failed_to_save_issues,
480 502 :count => unsaved_issue_ids.size,
481 503 :total => issues.size,
482 504 :ids => '#' + unsaved_issue_ids.join(', #'))
483 505 end
484 506 end
485 507
486 508 # Rescues an invalid query statement. Just in case...
487 509 def query_statement_invalid(exception)
488 510 logger.error "Query::StatementInvalid: #{exception.message}" if logger
489 511 session.delete(:query)
490 512 sort_clear if respond_to?(:sort_clear)
491 513 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
492 514 end
493 515
494 516 # Renders API response on validation failure
495 517 def render_validation_errors(object)
496 518 options = { :status => :unprocessable_entity, :layout => false }
497 519 options.merge!(case params[:format]
498 520 when 'xml'; { :xml => object.errors }
499 521 when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance
500 522 else
501 523 raise "Unknown format #{params[:format]} in #render_validation_errors"
502 524 end
503 525 )
504 526 render options
505 527 end
506 528
507 529 # Overrides #default_template so that the api template
508 530 # is used automatically if it exists
509 531 def default_template(action_name = self.action_name)
510 532 if api_request?
511 533 begin
512 534 return self.view_paths.find_template(default_template_name(action_name), 'api')
513 535 rescue ::ActionView::MissingTemplate
514 536 # the api template was not found
515 537 # fallback to the default behaviour
516 538 end
517 539 end
518 540 super
519 541 end
520 542
521 543 # Overrides #pick_layout so that #render with no arguments
522 544 # doesn't use the layout for api requests
523 545 def pick_layout(*args)
524 546 api_request? ? nil : super
525 547 end
526 548 end
General Comments 0
You need to be logged in to leave comments. Login now