From ca4695d43bb94fedb0b24657792636866ff4f6ae Mon Sep 17 00:00:00 2001 From: Timo Date: Tue, 15 May 2018 14:46:24 +0200 Subject: [PATCH] Allow custom cookie name to be set (#34) --- lib/angular_rails_csrf/concern.rb | 3 ++- test/angular_rails_csrf_test.rb | 21 +++++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/angular_rails_csrf/concern.rb b/lib/angular_rails_csrf/concern.rb index 07d2c52..1dda9ec 100644 --- a/lib/angular_rails_csrf/concern.rb +++ b/lib/angular_rails_csrf/concern.rb @@ -10,7 +10,8 @@ def set_xsrf_token_cookie if protect_against_forgery? && !respond_to?(:__exclude_xsrf_token_cookie?) config = Rails.application.config domain = config.respond_to?(:angular_rails_csrf_domain) ? config.angular_rails_csrf_domain : nil - cookies['XSRF-TOKEN'] = { value: form_authenticity_token, domain: domain } + cookie_name = config.respond_to?(:angular_rails_csrf_cookie_name) ? config.angular_rails_csrf_cookie_name : 'XSRF-TOKEN' + cookies[cookie_name] = { value: form_authenticity_token, domain: domain } end end diff --git a/test/angular_rails_csrf_test.rb b/test/angular_rails_csrf_test.rb index bce10c5..9be12a0 100644 --- a/test/angular_rails_csrf_test.rb +++ b/test/angular_rails_csrf_test.rb @@ -39,6 +39,15 @@ def config.angular_rails_csrf_domain; :all; end assert_response :success end + test "a custom name is used if present" do + use_custom_cookie_name do + get :index + assert @response.headers['Set-Cookie'].include?('CUSTOM-COOKIE-NAME') + assert_valid_cookie('CUSTOM-COOKIE-NAME') + assert_response :success + end + end + private # Helpers @@ -47,11 +56,19 @@ def set_header_to(value) @request.headers['X-XSRF-TOKEN'] = value end - def assert_valid_cookie + def assert_valid_cookie(name = 'XSRF-TOKEN') if @controller.respond_to?(:valid_authenticity_token?, true) - assert @controller.send(:valid_authenticity_token?, session, cookies['XSRF-TOKEN']) + assert @controller.send(:valid_authenticity_token?, session, cookies[name]) else assert_equal @controller.send(:form_authenticity_token), cookies['XSRF-TOKEN'] end end + + def use_custom_cookie_name + config = Rails.application.config + def config.angular_rails_csrf_cookie_name; 'CUSTOM-COOKIE-NAME'; end + yield + ensure + config.instance_eval('undef :angular_rails_csrf_cookie_name') + end end