Created
October 13, 2008 01:12
-
-
Save nakajima/16483 to your computer and use it in GitHub Desktop.
Easy basic auth for Sinatra actions
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
=begin | |
Easy Basic Authentication for Sinatra actions. | |
USAGE | |
require 'rubygems' | |
require 'sinatra' | |
require 'sinatra-auth' | |
get '/' do | |
protect! :username => 'admin', :password => 'sekret' | |
"This is protected by basic auth" | |
end | |
=end | |
module Sinatra | |
module Authorization | |
class ProtectedAction | |
attr_reader :credentials, :context | |
def initialize(context, credentials={}) | |
@credentials, @context = credentials, context | |
end | |
def check! | |
unauthorized! unless auth.provided? | |
bad_request! unless auth.basic? | |
unauthorized! unless authorize(*auth.credentials) | |
end | |
def remote_user | |
auth.username | |
end | |
private | |
def authorize(username, password) | |
credentials[:username] == username and credentials[:password] == password | |
end | |
def unauthorized! | |
context.header 'WWW-Authenticate' => %(Basic realm="#{credentials[:realm]}") | |
throw :halt, [ 401, 'Authorization Required' ] | |
end | |
def bad_request! | |
throw :halt, [ 400, 'Bad Request' ] | |
end | |
def auth | |
@auth ||= Rack::Auth::Basic::Request.new(context.request.env) | |
end | |
end | |
module Helpers | |
def protect!(credentials={}) | |
return if authorized? | |
guard = ProtectedAction.new(self, credentials) | |
guard.check! | |
request.env['REMOTE_USER'] = guard.remote_user | |
end | |
def authorized? | |
request.env['REMOTE_USER'] | |
end | |
end | |
end | |
end | |
helpers do | |
include Sinatra::Authorization::Helpers | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works awesome, but you have a typo in ln43
context.header 'WWW-Authenticate' => %(Basic realm="#{credentials[:realm]}")
It should be
context.headers 'WWW-Authenticate' => %(Basic realm="#{credentials[:realm]}")
Just missing an "s"Regards