From 1fd8dd85e8e68844f066096bd7d8438f753ddcc3 Mon Sep 17 00:00:00 2001 From: Justin Coyne Date: Fri, 15 Dec 2023 10:52:05 -0600 Subject: [PATCH] Set Allow-Origin header for probe requests --- .../iiif/auth/v2/probe_service_controller.rb | 22 ++++++++++++++----- config/routes.rb | 2 ++ .../iiif/auth/v2/probe_service_spec.rb | 11 ++++++++++ 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/app/controllers/iiif/auth/v2/probe_service_controller.rb b/app/controllers/iiif/auth/v2/probe_service_controller.rb index 77a8ebec..bee48898 100644 --- a/app/controllers/iiif/auth/v2/probe_service_controller.rb +++ b/app/controllers/iiif/auth/v2/probe_service_controller.rb @@ -15,18 +15,28 @@ def show file = StacksFile.new(id: parsed_uri[:druid], file_name: parsed_uri[:file_name], download: true) - response = { '@context': 'http://iiif.io/api/auth/2/context.json', type: 'AuthProbeResult2' } + json = { '@context': 'http://iiif.io/api/auth/2/context.json', type: 'AuthProbeResult2' } if !file.readable? - response[:status] = 404 + json[:status] = 404 elsif can? :access, file - response[:status] = 200 + json[:status] = 200 else - response[:status] = 401 - response.merge!(add_detail(file)) + json[:status] = 401 + json.merge!(add_detail(file)) end - render json: response + render json: + end + + # Because the probe request sets the Accept header, the browser is going to preflight the request. + # Here we tell the browser, yes, we're good with this. + def options_pre_flight + response.headers['Access-Control-Allow-Origin'] = '*' + response.headers['Access-Control-Allow-Methods'] = 'GET' + response.headers['Access-Control-Allow-Headers'] = 'Authorization' + response.headers['Access-Control-Max-Age'] = '1728000' + head :no_content end private diff --git a/config/routes.rb b/config/routes.rb index b9a9f947..ee163bac 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -84,4 +84,6 @@ # IIIF Auth V2 get '/iiif/auth/v2/token' => 'iiif/auth/v2/token#create' get '/iiif/auth/v2/probe' => 'iiif/auth/v2/probe_service#show' + options '/iiif/auth/v2/probe' => 'iiif/auth/v2/probe_service#options_pre_flight' + end diff --git a/spec/requests/iiif/auth/v2/probe_service_spec.rb b/spec/requests/iiif/auth/v2/probe_service_spec.rb index 2ad2dd18..891cb6f6 100644 --- a/spec/requests/iiif/auth/v2/probe_service_spec.rb +++ b/spec/requests/iiif/auth/v2/probe_service_spec.rb @@ -17,6 +17,17 @@ allow_any_instance_of(StacksFile).to receive(:readable?).and_return('420') end + describe 'pre-flight request' do + before do + options "/iiif/auth/v2/probe?id=#{stacks_uri_param}" + end + + it 'sets the headers' do + expect(response).to have_http_status :no_content + expect(response.headers['Access-Control-Allow-Origin']).to eq '*' + end + end + context 'when the URI is not properly encoded' do let(:file_name) { 'this has spaces.pdf' } let(:stacks_uri) { "https://stacks-uat.stanford.edu/file/druid:#{id}/#{file_name}" }