Using Authlogic and ActiveResource

Update, 6 July 2009: This code is outdated, designed around Authlogic 1. Thankfully, though, Joe Scharf (in the comments) has bundled up an HTTP-basic-authentication-via-API-key add-on for Authlogic 2. Well done, sir!

Out of the box, Authlogic identifies the current user by looking for four different values:

This is pretty awesome—most things you’d like to do Just Work.

But I’d like to make one small adjustment, since I’m using ActiveResource and following the example of the Highrise API: rather than doing HTTP basic authentication with the user’s login and password, I’d like to use an API key instead.

It turns out Authlogic makes this fairly easy:

class UserSession < Authlogic::Session::Base
  # Adjust how Authlogic identifies the current user.
  # The default setting is :params, :session, :cookie, :http_auth.
  find_with :session, :cookie, :api_key

  def valid_api_key?
    controller.authenticate_with_http_basic do |api_key, _|
      self.unauthorized_record = search_for_record("find_by_#{single_access_token_field}", api_key)
      self.persisting = false
      self.valid?
    end.tap do |authenticated|
      self.persisting = true unless authenticated
    end
  end
end

So now I can write a Widget Resource class like this:

class Widget < ActiveResource::Base
  self.site = 'http://localhost:3000/'
  self.user = 'MY_API_TOKEN'
end

Or poke around with curl:

# Create a new, empty Widget.
curl --user   'MY_API_TOKEN:X'                \
     --header 'Content-Type: application/xml' \
     --data   '<widget></widget>'             \
     http://localhost:3000/widgets.xml