views:

231

answers:

2

I have just begun adding a REST API on a rails app, and since I only wanted to expose a couple controller/actions, I added a method to ApplicationController:

  def http_basic_authentication
    if request.format == Mime::XML
      authenticate_or_request_with_http_basic do |username, api_key|
        self.current_user = User.find(:first, :from => 'users, accounts', :conditions => ["accounts.id = users.account_id AND accounts.api_key = ?", api_key])
      end
    end
  end

Which I can then use with a before_filter on my individual controller/actions that I want to expose. Does anyone have any feedback, code review, or a better approach?

A: 

Possibly this would be cleaner:

self.current_user = Account.find_by_api_key(api_key).user
Ben Alpert
That would work if there were not more than one user per account. Rather than making the API Key part of the User model, it is part of the Account model, and then when someone authenticates, it will be with their username and account.api_key. So I am not sure yours would really help.
Scott Miller
A: 

You may find useful the approach detailed here http://www.compulsivoco.com/2009/05/rails-api-authentication-using-restful-authentication/

This integrates with the common restful_authentication plugin.

simianarmy