Kickass Pixels

building success pixel by pixel

« Back to blog

Simple authentication for Sinatra in Rails Metal

Using Sinatra:Base to build Rails Metal is a joy and really speeds up the process.

I needed to protect API access with simple authentication and after trying a few routes I found this technique:
 
before do
  if request.env['PATH_INFO'].include?('/api/cool_stuff')
    Rack::Auth::Basic.new(request, 'API Access') do |username, password|
      Account.authenticate(username, password)
    end
  end
end

The trick was keeping the authentication from triggering for requests not meant for this path.

Loading mentions Retweet

Posted July 7, 2009
Jun 01, 2010
amikhailov said...
I'm doing authentication by that way:

before do
if @env['PATH_INFO'].match(/^\/api/) && user_id = @env['rack.session']['user_credentials_id']
sql = "select id from users where id = '#{user_id}'"
raise Sinatra::NotFound if User.connection.select_all(sql).blank?
else
raise Sinatra::NotFound
end
end

Jun 02, 2010
Lon Baker said...
Amik, thanks. I like the way you incorporated the session/cookie check into the process. I like to keep SQL in my models, so I would pass the credentials as an argument to a model method.
 
To leave a comment on this posterous, please login by clicking one of the following.
Posterous-login     twitter