Skip to content

Instantly share code, notes, and snippets.

@bryanl
Created May 11, 2009 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanl/110044 to your computer and use it in GitHub Desktop.
Save bryanl/110044 to your computer and use it in GitHub Desktop.
module Sinatra
module Authorization
def auth
@auth ||= Rack::Auth::Basic::Request.new(request.env)
end
def unauthorized!(realm="flixcloud.com")
response['WWW-Authenticate'] = %(Basic realm="#{realm}")
throw :halt, [ 401, 'Authorization Required' ]
end
def bad_request!
throw :halt, [ 400, 'Bad Request' ]
end
def authorized?
request.env['REMOTE_USER']
end
def authorize(username, password)
# Insert your logic here to determine if username/password is good
false
end
def require_authorization
return if authorized?
unauthorized! unless auth.provided?
bad_request! unless auth.basic?
unauthorized! unless authorize(*auth.credentials)
request.env['REMOTE_USER'] = auth.username
end
def admin?
authorized?
end
end
end
require 'sinatra/authorization'
class Whatever < Sinatra::Base
helpers do
include Sinatra::Authorization
def authorize(username, password)
User.authenticate(username, password)
end
end
get '/something' do
require_authorization
# Do some other crap
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment