Skip to content

Instantly share code, notes, and snippets.

@joshhepworth
Created September 3, 2013 18:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshhepworth/6427698 to your computer and use it in GitHub Desktop.
Save joshhepworth/6427698 to your computer and use it in GitHub Desktop.
Setup basic auth as a middleware for a rack application.
class Lockdown
def initialize(app)
@app = app
end
def call(env)
request = Rack::Request.new(env)
if request.path != '/'
auth = Rack::Auth::Basic::Request.new(env)
return unauthorized unless auth.provided?
return bad_request unless auth.basic?
if auth.credentials == [username, password]
env['REMOTE_USER'] = auth.username
return @app.call(env)
end
unauthorized
else
@app.call(env)
end
end
private
def username
'username'
end
def password
'password'
end
def unauthorized(www_authenticate = challenge)
return [ 401,
{ 'Content-Type' => 'text/plain',
'Content-Length' => '0',
'WWW-Authenticate' => www_authenticate.to_s },
[]
]
end
def bad_request
return [ 400,
{ 'Content-Type' => 'text/plain',
'Content-Length' => '0' },
[]
]
end
def challenge
'Basic realm="%s"' % realm
end
def realm
'Realm'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment