Created
July 15, 2010 00:33
-
-
Save itspriddle/476335 to your computer and use it in GitHub Desktop.
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
# Put this in app/metals/api.rb | |
require 'sinatra/base' | |
class Api < Sinatra::Base | |
before do | |
content_type :json | |
authenticate if api_request? | |
end | |
helpers do | |
def api_request? | |
request.path_info.match %r{/api/}i | |
end | |
def authenticate | |
unless authenticated? | |
response['WWW-Authenticate'] = %(Basic realm="My API") | |
throw(:halt, [401, "Unauthorized\n"]) | |
end | |
end | |
def authenticated? | |
auth = Rack::Auth::Basic::Request.new(request.env) | |
auth.provided? && auth.basic? && | |
auth.credentials && @current_user = User.authenticate(*auth.credentials) | |
end | |
def current_user | |
@current_user | |
end | |
end | |
get '/api/account.json' do | |
current_user.to_json | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment