Created
July 23, 2010 18:11
-
-
Save itspriddle/487806 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'sinatra_authentication' | |
class Api < Sinatra::Base | |
register ::MyApp::Sinatra::Authentication | |
get '/api/ping' do | |
render "Authentication successful" | |
end | |
end |
This file contains hidden or 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
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 |
This file contains hidden or 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
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