Skip to content

Instantly share code, notes, and snippets.

@itspriddle
Created July 15, 2010 00:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itspriddle/476335 to your computer and use it in GitHub Desktop.
Save itspriddle/476335 to your computer and use it in GitHub Desktop.
# 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