Skip to content

Commit

Permalink
Improve api error messages on api key expiring and being disabled
Browse files Browse the repository at this point in the history
  • Loading branch information
mlandauer committed Sep 17, 2024
1 parent f98cded commit 8b61ec3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
15 changes: 13 additions & 2 deletions app/controllers/api_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,19 @@ def require_api_key
return if @current_api_key
end

# TODO: Show different errors for when a key has been disabled and when it has expired
render_error("not authorised - use a valid api key", :unauthorized)
# TODO: Refactor this
key = ApiKey.find_by(value: params_key)

reason = if key.nil?
"use a valid api key"
elsif key.expired?
"api key has expired"
elsif key.disabled?
"api key is disabled"
else
raise "Unexpected"
end
render_error("not authorised - #{reason}", :unauthorized)
end

sig { void }
Expand Down
21 changes: 20 additions & 1 deletion spec/controllers/api_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@
it { expect(subject.body).to eq '{"error":"not authorised - use a valid api key"}' }
end

shared_examples "not authorised disabled" do
it { expect(subject.status).to eq 401 }
it { expect(subject.body).to eq '{"error":"not authorised - api key is disabled"}' }
end

shared_examples "not authorised expired" do
it { expect(subject.status).to eq 401 }
it { expect(subject.body).to eq '{"error":"not authorised - api key has expired"}' }
end

context "when no API key is given" do
subject { get method, params: params.merge(key: nil) }

Expand All @@ -34,7 +44,16 @@
get method, params: params.merge(key: key.value)
end

include_examples "not authorised"
include_examples "not authorised disabled"
end

context "when user has an expired api key" do
subject do
key = create(:api_key, expires_at: 7.days.ago)
get method, params: params.merge(key: key.value)
end

include_examples "not authorised expired"
end
end

Expand Down

0 comments on commit 8b61ec3

Please sign in to comment.