Skip to content

Commit

Permalink
Merge pull request #55 from square/alexc-dynamic-injection
Browse files Browse the repository at this point in the history
Allow dynamic injection of credentials
  • Loading branch information
drcapulet committed Dec 5, 2019
2 parents 7b490a2 + bc10c1a commit fa93db5
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGES.md
@@ -1,5 +1,9 @@
### Unreleased

* [#55](https://github.com/square/rails-auth/pull/55)
Allow dynamic injection of credentials.
([@drcapulet])

* [#59](https://github.com/square/rails-auth/pull/59)
Expose X.509 Subject Alternative Name extension
in the Rails::Auth::X509::Certificate and provide a convenience
Expand Down
6 changes: 4 additions & 2 deletions lib/rails/auth/credentials/injector_middleware.rb
Expand Up @@ -5,15 +5,17 @@ module Auth
class Credentials
# A middleware for injecting an arbitrary credentials hash into the Rack environment
# This is intended for development and testing purposes where you would like to
# simulate a given X.509 certificate being used in a request or user logged in
# simulate a given X.509 certificate being used in a request or user logged in.
# The credentials argument should either be a hash or a proc that returns one.
class InjectorMiddleware
def initialize(app, credentials)
@app = app
@credentials = credentials
end

def call(env)
env[Rails::Auth::Env::CREDENTIALS_ENV_KEY] = @credentials
credentials = @credentials.respond_to?(:call) ? @credentials.call(env) : @credentials
env[Rails::Auth::Env::CREDENTIALS_ENV_KEY] = credentials
@app.call(env)
end
end
Expand Down
13 changes: 13 additions & 0 deletions spec/rails/auth/credentials/injector_middleware_spec.rb
Expand Up @@ -10,4 +10,17 @@
_response, env = middleware.call(request)
expect(env[Rails::Auth::Env::CREDENTIALS_ENV_KEY]).to eq credentials
end

context "with a proc for credentials" do
let(:credentials_proc) { instance_double(Proc) }
let(:middleware) { described_class.new(app, credentials_proc) }

it "overrides rails-auth credentials in the rack environment" do
expect(credentials_proc).to receive(:call).with(request).and_return(credentials)

_response, env = middleware.call(request)

expect(env[Rails::Auth::Env::CREDENTIALS_ENV_KEY]).to eq credentials
end
end
end

0 comments on commit fa93db5

Please sign in to comment.