diff options
Diffstat (limited to 'activesupport/lib/active_support/messages/metadata.rb')
-rw-r--r-- | activesupport/lib/active_support/messages/metadata.rb | 49 |
1 files changed, 32 insertions, 17 deletions
diff --git a/activesupport/lib/active_support/messages/metadata.rb b/activesupport/lib/active_support/messages/metadata.rb index a45aecfcd0..e97caac766 100644 --- a/activesupport/lib/active_support/messages/metadata.rb +++ b/activesupport/lib/active_support/messages/metadata.rb @@ -5,27 +5,25 @@ require "time" module ActiveSupport module Messages #:nodoc: class Metadata #:nodoc: - def initialize(expires_at, purpose) - @expires_at, @purpose = expires_at, purpose.to_s + def initialize(message, expires_at = nil, purpose = nil) + @message, @expires_at, @purpose = message, expires_at, purpose + end + + def as_json(options = {}) + { _rails: { message: @message, exp: @expires_at, pur: @purpose } } end class << self def wrap(message, expires_at: nil, expires_in: nil, purpose: nil) if expires_at || expires_in || purpose - { "value" => message, "_rails" => { "exp" => pick_expiry(expires_at, expires_in), "pur" => purpose } } + JSON.encode new(encode(message), pick_expiry(expires_at, expires_in), purpose) else message end end def verify(message, purpose) - metadata = extract_metadata(message) - - if metadata.nil? - message if purpose.nil? - elsif metadata.match?(purpose) && metadata.fresh? - message["value"] - end + extract_metadata(message).verify(purpose) end private @@ -38,19 +36,36 @@ module ActiveSupport end def extract_metadata(message) - if message.is_a?(Hash) && message.key?("_rails") - new(message["_rails"]["exp"], message["_rails"]["pur"]) + data = JSON.decode(message) rescue nil + + if data.is_a?(Hash) && data.key?("_rails") + new(decode(data["_rails"]["message"]), data["_rails"]["exp"], data["_rails"]["pur"]) + else + new(message) end end - end - def match?(purpose) - @purpose == purpose.to_s + def encode(message) + ::Base64.strict_encode64(message) + end + + def decode(message) + ::Base64.strict_decode64(message) + end end - def fresh? - @expires_at.nil? || Time.now.utc < Time.iso8601(@expires_at) + def verify(purpose) + @message if match?(purpose) && fresh? end + + private + def match?(purpose) + @purpose.to_s == purpose.to_s + end + + def fresh? + @expires_at.nil? || Time.now.utc < Time.iso8601(@expires_at) + end end end end |