Created
September 3, 2013 18:28
-
-
Save joshhepworth/6427698 to your computer and use it in GitHub Desktop.
Setup basic auth as a middleware for a rack application.
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
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