diff --git a/app/controllers/api/cors_controller.rb b/app/controllers/api/cors_controller.rb new file mode 100644 index 000000000..c060cd6a1 --- /dev/null +++ b/app/controllers/api/cors_controller.rb @@ -0,0 +1,20 @@ +module Api + class CorsController < ApplicationController + skip_before_action :verify_authenticity_token + skip_authorization_check + + def cors_preflight_check + set_access_control_headers + render json: { status: :ok } + end + + def set_access_control_headers + response.headers['Access-Control-Allow-Origin'] = '*' + response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, PATCH, DELETE, OPTIONS' + response.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, ' \ + 'Authorization, Token, Auth-Token, '\ + 'Email, X-User-Token, X-User-Email' + response.headers['Access-Control-Max-Age'] = '3600' + end + end +end diff --git a/config/routes.rb b/config/routes.rb index ff33ec652..87915e12f 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -29,6 +29,9 @@ Rails.application.routes.draw do resources :contacts, only: %i[index show], param: :uuid end end + + match '*all', controller: 'cors', action: 'cors_preflight_check', via: [:options], + as: 'cors_preflight_check' end # REGISTRAR ROUTES diff --git a/test/integration/api/registrant/registrant_api_cors_headers_test.rb b/test/integration/api/registrant/registrant_api_cors_headers_test.rb new file mode 100644 index 000000000..54cb5894e --- /dev/null +++ b/test/integration/api/registrant/registrant_api_cors_headers_test.rb @@ -0,0 +1,21 @@ +require 'test_helper' + +class RegistrantApiCorsHeadersTest < ApplicationIntegrationTest + def test_returns_200_response_code_for_options_request + options '/api/v1/registrant/auth/eid', {} + + assert_equal('200', response.code) + end + + def test_returns_expected_headers_for_options_requests + options '/api/v1/registrant/auth/eid', {}, { 'Origin' => 'https://example.com' } + + assert_equal('*', response.headers['Access-Control-Allow-Origin']) + assert_equal('POST, GET, PUT, PATCH, DELETE, OPTIONS', + response.headers['Access-Control-Allow-Methods']) + assert_equal('Origin, Content-Type, Accept, Authorization, Token, Auth-Token, Email, ' \ + 'X-User-Token, X-User-Email', + response.headers['Access-Control-Allow-Headers']) + assert_equal('3600', response.headers['Access-Control-Max-Age']) + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index 64e308de8..ce5666ece 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -28,6 +28,13 @@ class ActiveSupport::TestCase end end +# Allows testing OPTIONS request just like GET or POST +module ActionDispatch::Integration::RequestHelpers + def options(path, parameters = nil, headers_or_env = nil) + process :options, path, parameters, headers_or_env + end +end + class ApplicationIntegrationTest < ActionDispatch::IntegrationTest include Capybara::DSL include Capybara::Minitest::Assertions