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