2011-05-31 06:24:30 -04:00
|
|
|
require 'active_support/core_ext/module/delegation'
|
|
|
|
|
2010-07-08 12:16:36 -04:00
|
|
|
module ActiveModel
|
2010-01-29 20:02:12 -05:00
|
|
|
module MassAssignmentSecurity
|
2011-05-26 08:58:43 -04:00
|
|
|
class Sanitizer
|
2011-05-31 06:24:30 -04:00
|
|
|
def initialize(target=nil)
|
|
|
|
end
|
|
|
|
|
2010-01-29 20:02:12 -05:00
|
|
|
# Returns all attributes not denied by the authorizer.
|
2011-05-26 08:58:43 -04:00
|
|
|
def sanitize(attributes, authorizer)
|
|
|
|
sanitized_attributes = attributes.reject { |key, value| authorizer.deny?(key) }
|
2010-07-08 13:02:34 -04:00
|
|
|
debug_protected_attribute_removal(attributes, sanitized_attributes)
|
2010-01-29 20:02:12 -05:00
|
|
|
sanitized_attributes
|
|
|
|
end
|
|
|
|
|
2010-07-08 13:02:34 -04:00
|
|
|
protected
|
2010-01-29 20:02:12 -05:00
|
|
|
|
2010-07-08 13:02:34 -04:00
|
|
|
def debug_protected_attribute_removal(attributes, sanitized_attributes)
|
|
|
|
removed_keys = attributes.keys - sanitized_attributes.keys
|
2011-05-26 08:58:43 -04:00
|
|
|
process_removed_attributes(removed_keys) if removed_keys.any?
|
2010-07-08 13:02:34 -04:00
|
|
|
end
|
2011-06-12 11:31:21 -04:00
|
|
|
|
2011-05-26 08:58:43 -04:00
|
|
|
def process_removed_attributes(attrs)
|
|
|
|
raise NotImplementedError, "#process_removed_attributes(attrs) suppose to be overwritten"
|
|
|
|
end
|
|
|
|
end
|
2011-05-31 06:24:30 -04:00
|
|
|
|
2011-05-30 04:34:00 -04:00
|
|
|
class LoggerSanitizer < Sanitizer
|
2011-05-31 06:24:30 -04:00
|
|
|
delegate :logger, :to => :@target
|
2010-07-07 11:05:42 -04:00
|
|
|
|
2011-05-31 06:24:30 -04:00
|
|
|
def initialize(target)
|
|
|
|
@target = target
|
|
|
|
super
|
|
|
|
end
|
2011-05-26 08:58:43 -04:00
|
|
|
|
2011-05-31 06:24:30 -04:00
|
|
|
def logger?
|
|
|
|
@target.respond_to?(:logger) && @target.logger
|
2011-05-26 08:58:43 -04:00
|
|
|
end
|
2011-05-31 06:24:30 -04:00
|
|
|
|
2011-05-26 08:58:43 -04:00
|
|
|
def process_removed_attributes(attrs)
|
2011-05-31 06:24:30 -04:00
|
|
|
logger.debug "WARNING: Can't mass-assign protected attributes: #{attrs.join(', ')}" if logger?
|
2010-07-08 13:02:34 -04:00
|
|
|
end
|
2010-01-29 20:02:12 -05:00
|
|
|
end
|
2011-05-30 04:34:00 -04:00
|
|
|
|
|
|
|
class StrictSanitizer < Sanitizer
|
|
|
|
def process_removed_attributes(attrs)
|
2011-07-28 04:56:08 -04:00
|
|
|
return if (attrs - insensitive_attributes).empty?
|
2011-05-30 04:34:00 -04:00
|
|
|
raise ActiveModel::MassAssignmentSecurity::Error, "Can't mass-assign protected attributes: #{attrs.join(', ')}"
|
|
|
|
end
|
2011-07-28 04:56:08 -04:00
|
|
|
|
|
|
|
def insensitive_attributes
|
|
|
|
['id']
|
|
|
|
end
|
2011-05-30 04:34:00 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
class Error < StandardError
|
|
|
|
end
|
2010-01-29 20:02:12 -05:00
|
|
|
end
|
|
|
|
end
|