user315252
user315252

Reputation: 179

Implementing API for a Rails app

I am building an API for my rails app i am trying to reuse same controllers for both API and app logic. The requests without authenticating a user is fine but how to implement if some actions need an authentication. I am using authlogic, to edit people need some specific permissions which i am checking in the before_filter. If i implement an API using http basic authentication how do i differentiate ?

Upvotes: 0

Views: 973

Answers (2)

DanSingerman
DanSingerman

Reputation: 36532

I think there are two parts to the answer. Firstly you need to set up http basic auth with authlogic. The details for doing that are contained in this SO answer: Rails: Basic Authentication with Authlogic

Then you need to differentiate between API calls and normal browser calls in your controller. Assuming your API is XML or JSON, you can do that with something like this:

class ThingsController < ApplicationController
   before_filter :authorize

   def authorize
      if params[:format] == 'json' || params[:format] == 'xml' 
         require_http_auth_user # http basic auth for API access
      else
         require_user # normal authlogic authentication 
      end
   end
end

Upvotes: 1

Ant
Ant

Reputation: 3887

It may be worthwhile separating into two separate controllers and including the common functionality via a mixin. That way you can auth the controllers separately.

Upvotes: 0

Related Questions