Skip to content

Commit

Permalink
Allow custom cookie name to be set (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
timobleeker authored and bodrovis committed May 15, 2018
1 parent a8342d7 commit ca4695d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
3 changes: 2 additions & 1 deletion lib/angular_rails_csrf/concern.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
21 changes: 19 additions & 2 deletions test/angular_rails_csrf_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

0 comments on commit ca4695d

Please sign in to comment.