Skip to content

Instantly share code, notes, and snippets.

@itspriddle
Created July 23, 2010 18:11
Show Gist options
  • Save itspriddle/487806 to your computer and use it in GitHub Desktop.
Save itspriddle/487806 to your computer and use it in GitHub Desktop.
require 'sinatra_authentication'
class Api < Sinatra::Base
register ::MyApp::Sinatra::Authentication
get '/api/ping' do
render "Authentication successful"
end
end
module MyApp
module Sinatra
module Authentication
def self.registered(app)
app.before do
content_type :json
authenticate if api_request?
end
app.helpers Helpers
end
module Helpers
def api_request?
request.path_info.match %r{^/api/}i
end
def authenticate
unless authenticated?
response['WWW-Authenticate'] = %(Basic realm="API")
throw(:halt, error('Unauthorized', 401))
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
def render(output, code = 200)
out = { :response => output }.to_json + "\n"
[code.to_i, out]
end
def error(output = 'ERROR', code = 400)
render(output, code)
end
end
end
end
end
class User < ActiveRecord::Base
acts_as_authentic
def self.authenticate(username, password)
c = find_by_username(username)
c && c.valid_password?(password) ? c : nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment