Skip to content

Instantly share code, notes, and snippets.

@mildmojo
Created June 21, 2012 18:07
Show Gist options
  • Save mildmojo/2967459 to your computer and use it in GitHub Desktop.
Save mildmojo/2967459 to your computer and use it in GitHub Desktop.
Sitewide Rack HTTP basic auth with exceptions for publicly-accessible paths
require File.expand_path("../init", __FILE__)
require 'rack/ssl-enforcer'
# Require HTTPS for all requests (not required; remove if unavailable)
use Rack::SslEnforcer
AUTH_CREDS = { user: 'user', pass: 'password' }
# Create a middleware to add HTTP basic auth to all but the whitelisted paths
class ProtectedApp
WHITELIST_PATH_REGEX = %r{/.*?/status_icon$}
def initialize(app, realm=nil, &authenticator)
@app = app
@authenticator = Rack::Auth::Basic.new( app, &authenticator )
end
def call(env)
request = Rack::Request.new(env)
request.path.match( WHITELIST_PATH_REGEX ) ? @app.call(env) : @authenticator.call(env)
end
end
use ProtectedApp do |user, pass|
user == AUTH_CREDS[:user] && pass == AUTH_CREDS[:pass]
end
map "/" do
run MySinatra.app
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment