Created
August 19, 2016 08:47
-
-
Save trekdemo/1500ad900065f3b48453bd4a19307628 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'base64' | |
require 'uri' | |
require 'faraday' | |
module FaradayMiddleware | |
class BasicAuthOverwrite < Faraday::Middleware | |
KEY = "Authorization".freeze | |
def call(env) | |
rewrite_request(env) | |
@app.call(env) | |
end | |
private | |
def rewrite_request(env) | |
url = env[:url] | |
user = url.user | |
pass = url.password | |
return unless user && pass | |
# Nullify the user and password components of the url | |
# We don't want to send them plain | |
url.user = nil | |
url.password = nil | |
# Set the Authorization header | |
value = Base64.encode64([user, pass].join(':')).gsub("\n", '') | |
env.request_headers[KEY] = "Basic #{value}" | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'faraday_middleware/basic_auth_overwrite' | |
module FaradayMiddleware | |
RSpec.describe BasicAuthOverwrite do | |
def new_client(method) | |
Faraday.new do |builder| | |
builder.use described_class | |
builder.adapter :test do |stub| | |
stub.send(method, '/') { |env| | |
[200, {}, env.request_headers['Authorization']] | |
} | |
end | |
end | |
end | |
context 'when url contains username and password' do | |
it 'adds Authorization headers' do | |
client = new_client(:post) | |
result = client.post('http://user:[email protected]/') | |
expect(result.env[:url]).to eq(URI('http://example.com/')) | |
encoded_credentials = result.body.sub('Basic ', '') | |
expect(Base64.decode64(encoded_credentials)).to eq('user:password') | |
end | |
end | |
context 'when url does not contain credentials' do | |
it 'does not add authorization headers' do | |
client = new_client(:post) | |
result = client.post('http://example.com/') | |
expect(result.env[:url]).to eq(URI('http://example.com/')) | |
expect(result.body).to be_nil | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment