Skip to content

Commit

Permalink
Add API::Client#database_connection
Browse files Browse the repository at this point in the history
  • Loading branch information
aurelien-reeves-scalingo committed Dec 21, 2022
1 parent b31802e commit 387a4e1
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/scalingo/api/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,24 @@ def authenticated_connection
conn.adapter(config.faraday_adapter) if config.faraday_adapter
}
end

def database_connection(database_id)
raise Error::Unauthenticated unless token_holder.authenticated_for_database?(database_id)

@database_connections ||= Hash.new
@database_connections[database_id] ||= Faraday.new(connection_options) { |conn|
conn.response :json, content_type: /\bjson$/, parser_options: {symbolize_names: true}
conn.request :json

bearer_token = token_holder.database_tokens[database_id]&.value
if bearer_token
auth_header = Faraday::Request::Authorization.header "Bearer", bearer_token
conn.headers[Faraday::Request::Authorization::KEY] = auth_header
end

conn.adapter(config.faraday_adapter) if config.faraday_adapter
}
end
end
end
end
41 changes: 41 additions & 0 deletions spec/scalingo/api/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,47 @@
end
end

describe "database_connection" do
let(:database_id) { "db-id-1234" }

context "without bearer token" do
let(:scalingo) { scalingo_guest }

it "raises" do
expect {
subject.database_connection(database_id)
}.to raise_error(Scalingo::Error::Unauthenticated)
end
end

context "with bearer token" do
it "has an authentication header set with a bearer scheme" do
scalingo.authenticate_database_with_bearer_token(
database_id,
"1234",
expires_at: Time.now + 1.hour,
raise_on_expired_token: false
)
expect(subject.database_connection(database_id).headers["Authorization"]).to eq "Bearer #{subject.token_holder.database_tokens[database_id].value}"
end
end

context "with wrong bearer token" do
it "raises" do
database_id_2 = "db-id-5678"
scalingo.authenticate_database_with_bearer_token(
database_id_2,
"1234",
expires_at: Time.now + 1.hour,
raise_on_expired_token: false
)
expect {
subject.database_connection(database_id)
}.to raise_error(Scalingo::Error::Unauthenticated)
end
end
end

describe "connection" do
context "logged" do
context "no fallback to guest" do
Expand Down

0 comments on commit 387a4e1

Please sign in to comment.