Skip to content

Instantly share code, notes, and snippets.

@alexsergeyev
Created March 21, 2011 18:57
Show Gist options
  • Save alexsergeyev/879977 to your computer and use it in GitHub Desktop.
Save alexsergeyev/879977 to your computer and use it in GitHub Desktop.

Revisions

  1. alexsergeyev created this gist Mar 21, 2011.
    37 changes: 37 additions & 0 deletions api.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    # 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