Skip to content

Instantly share code, notes, and snippets.

@alexsergeyev
Created March 21, 2011 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexsergeyev/879977 to your computer and use it in GitHub Desktop.
Save alexsergeyev/879977 to your computer and use it in GitHub Desktop.
Sinatra metal with Rails authentification
# 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