Skip to content

Instantly share code, notes, and snippets.

@dekart
Created November 25, 2009 09:09
Show Gist options
  • Save dekart/242584 to your computer and use it in GitHub Desktop.
Save dekart/242584 to your computer and use it in GitHub Desktop.
# Add this your environment.rb or environment/*.rb file
config.middleware.use(::Rack::Middleware::BasicAuth,
:username => "myuser",
:password => "my$uperpa$$vvord",
:domain => "mydomain.com"
)
module Rack
module Middleware
class BasicAuth
def initialize(app, options = {})
@app = app
@options = options
end
def call(env, options = {})
unless env['REMOTE_USER']
auth = Rack::Auth::Basic::Request.new(env)
return unauthorized! unless auth.provided?
return bad_request! unless auth.basic?
return unauthorized! unless authorize(*auth.credentials)
env['REMOTE_USER'] = auth.username
end
@app.call(env)
end
def authorize(username, password)
@options[:username] == username && @options[:password] == password
end
def unauthorized!
[ 401, {'WWW-Authenticate' => %(Basic realm="#{@options[:domain]}")}, 'Authorization Required' ]
end
def bad_request!
[ 400, 'Bad Request' ]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment