From e158ee50e64e2ae2460cd26be53039922f588300 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sun, 17 Aug 2014 12:40:24 -0700 Subject: Use AS::JSON for (de)serializing cookies Use the Active Support JSON encoder for cookie jars using the `:json` or `:hybrid` serializer. This allows you to serialize custom Ruby objects into cookies by defining the `#as_json` hook on such objects. Fixes #16520. --- actionpack/test/dispatch/cookies_test.rb | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'actionpack/test/dispatch/cookies_test.rb') diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index 7e7dd94425..9b03c805a0 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -21,6 +21,16 @@ class CookiesTest < ActionController::TestCase end end + class JSONWrapper + def initialize(obj) + @obj = obj + end + + def as_json(options = nil) + "wrapped: #{@obj.as_json(options)}" + end + end + class TestController < ActionController::Base def authenticate cookies["user_name"] = "david" @@ -85,6 +95,11 @@ class CookiesTest < ActionController::TestCase head :ok end + def set_wrapped_signed_cookie + cookies.signed[:user_id] = JSONWrapper.new(45) + head :ok + end + def get_signed_cookie cookies.signed[:user_id] head :ok @@ -95,6 +110,11 @@ class CookiesTest < ActionController::TestCase head :ok end + def set_wrapped_encrypted_cookie + cookies.encrypted[:foo] = JSONWrapper.new('bar') + head :ok + end + def get_encrypted_cookie cookies.encrypted[:foo] head :ok @@ -421,6 +441,14 @@ class CookiesTest < ActionController::TestCase assert_equal 45, cookies.signed[:user_id] end + def test_wrapped_signed_cookie_using_json_serializer + @request.env["action_dispatch.cookies_serializer"] = :json + get :set_wrapped_signed_cookie + cookies = @controller.send :cookies + assert_not_equal 'wrapped: 45', cookies[:user_id] + assert_equal 'wrapped: 45', cookies.signed[:user_id] + end + def test_signed_cookie_using_custom_serializer @request.env["action_dispatch.cookies_serializer"] = CustomSerializer get :set_signed_cookie @@ -503,6 +531,17 @@ class CookiesTest < ActionController::TestCase assert_equal 'bar', cookies.encrypted[:foo] end + def test_wrapped_encrypted_cookie_using_json_serializer + @request.env["action_dispatch.cookies_serializer"] = :json + get :set_wrapped_encrypted_cookie + cookies = @controller.send :cookies + assert_not_equal 'wrapped: bar', cookies[:foo] + assert_raises ::JSON::ParserError do + cookies.signed[:foo] + end + assert_equal 'wrapped: bar', cookies.encrypted[:foo] + end + def test_encrypted_cookie_using_custom_serializer @request.env["action_dispatch.cookies_serializer"] = CustomSerializer get :set_encrypted_cookie -- cgit v1.2.3