Skip to content

Instantly share code, notes, and snippets.

@cheald
Created December 3, 2013 23:34
Show Gist options
  • Save cheald/7779685 to your computer and use it in GitHub Desktop.
Save cheald/7779685 to your computer and use it in GitHub Desktop.
class ActionDispatch::Flash::FlashHash
alias_method :original_initialize, :initialize
def initialize #:nodoc:
original_initialize
@flashes = HashWithIndifferentAccess.new
end
def as_json(options = {})
[@flashes.as_json(options), @used.to_a.as_json(options), @now]
end
def from_json(flashes = {}, used = [], now = nil)
update flashes
@used = Set.new(used)
@now = FlashNow.new(self) if @now
end
alias_method :original_replace, :replace
def replace(h)
original_replace h.with_indifferent_access
end
def self.from_json(struct)
struct = [{}, [], nil] unless struct.is_a? Array
new.tap {|obj| obj.from_json(*struct) }
end
protected
alias_method :original_use, :use
def use(key = nil, used = true)
key = key.to_s if key
original_use(key, used)
end
end
class ActionDispatch::Flash::FlashNow
def as_json(options = {})
true
end
end
module ActiveSupport
class JsonCookieMessageVerifier < MessageVerifier
def verify(signed_message)
raise InvalidSignature if signed_message.blank?
data, digest = signed_message.split("--")
if data.present? && digest.present? && secure_compare(digest, generate_digest(data))
str = ::Base64.decode64(data)
begin
result = JSON.decode(str)
result = deep_indifferent_access result
if result.key? "flash"
result["flash"] = ActionDispatch::Flash::FlashHash.from_json result["flash"]
end
result
rescue
{}.with_indifferent_access
end
else
raise InvalidSignature
end
end
def generate(value)
data = ::Base64.strict_encode64(JSON.encode value)
"#{data}--#{generate_digest(data)}"
end
private
def deep_indifferent_access(value)
case value
when Array
value.map {|val| deep_indifferent_access val }
when Hash
value.with_indifferent_access.tap do |ival|
ival.keys.each do |key|
ival[key] = deep_indifferent_access ival[key]
end
end
else
value
end
end
end
end
class ActionDispatch::Cookies::SignedCookieJar
def initialize(parent_jar, secret)
ensure_secret_secure(secret)
@parent_jar = parent_jar
@verifier = ActiveSupport::JsonCookieMessageVerifier.new(secret)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment