Created
March 21, 2011 18:57
-
-
Save alexsergeyev/879977 to your computer and use it in GitHub Desktop.
Sinatra metal with Rails authentification
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
# Allow the metal piece to run in isolation | |
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails) | |
require 'sinatra' | |
class Api < Sinatra::Application | |
helpers do | |
def protected! | |
unless authorized? | |
response['WWW-Authenticate'] = %(Basic realm="Restricted Area") | |
throw(:halt, [401, "Not authorized\n"]) | |
end | |
end | |
def authorized? | |
if env["rack.session"][:user] | |
@current_user = User.find(env["rack.session"][:user]) | |
else | |
@auth ||= Rack::Auth::Basic::Request.new(request.env) | |
if @auth.provided? && @auth.basic? && @auth.credentials | |
@current_user = User.authenticate(*@auth.credentials) | |
end | |
end | |
end | |
end | |
before do | |
protected! if request.path =~ /^\/api/ | |
end | |
get '/api/test/' do | |
@current_user.email | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment