Raise errors on DFC requests

The simplified API was only returning the response body, not allowing us
to inspect if an error occurred. Since an error should be an exception
when communicating with a standardised protocol, we raise an error and
keep our simple API.
This commit is contained in:
Maikel Linke
2024-08-23 14:42:28 +10:00
parent 98966f6b89
commit 439f0cac64
2 changed files with 17 additions and 8 deletions

View File

@@ -14,9 +14,12 @@ class DfcRequest
end
def call(url, data = nil)
response = request(url, data)
begin
response = request(url, data)
rescue Faraday::UnauthorizedError, Faraday::ForbiddenError
raise unless token_stale?
if response.status >= 400 && token_stale?
# If access was denied and our token is stale then refresh and retry:
refresh_access_token!
response = request(url, data)
end
@@ -47,7 +50,10 @@ class DfcRequest
'Content-Type' => 'application/json',
'Authorization' => "Bearer #{@user.oidc_account.token}",
}
)
) do |f|
# Configure Faraday to raise errors on status 4xx and 5xx responses.
f.response :raise_error
end
end
def only_public_connections(&)

View File

@@ -40,11 +40,13 @@ RSpec.describe DfcRequest do
expect {
api.call("http://example.net/api")
}.to change {
account.token
}.and change {
account.refresh_token
}
.to raise_error(Faraday::UnauthorizedError)
.and change {
account.token
}.and change {
account.refresh_token
}
end
it "doesn't try to refresh the token when it's still fresh" do
@@ -53,7 +55,8 @@ RSpec.describe DfcRequest do
user.oidc_account.updated_at = 1.minute.ago
expect(api.call("http://example.net/api")).to eq ""
expect { api.call("http://example.net/api") }
.to raise_error(Faraday::UnauthorizedError)
# Trying to reach the OIDC server via network request to refresh the token
# would raise errors because we didn't setup Webmock or VCR.