Created
June 21, 2012 18:07
-
-
Save mildmojo/2967459 to your computer and use it in GitHub Desktop.
Sitewide Rack HTTP basic auth with exceptions for publicly-accessible paths
This file contains hidden or 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
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