4

We're upgrading an application that has two ways of authenticating users.

  1. Controllers that have the before_filter :authenticate_user! callback and are accessed like a standard Rails site.
  2. Controllers inside an API module that are accessed via JSON by client side applications. All the routes have the prefix /api/session_id/ except the authenticate action that only has the prefix /api.

Both ways authenticate the users using the User model.

Is there a way to configure devise to support them both? How?

Note: I don't want to create users through JSON. I just want to authenticate them.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
dcarneiro
  • 7,060
  • 11
  • 51
  • 74

2 Answers2

0

I did this by overriding devise's session controller.

Add entry to routes for custom session controller:

 devise_for :users, :controllers => {:sessions => 'sessions'}

And override the session controller:

  class SessionsController < Devise::SessionsController

    def create
      resource = warden.authenticate!(:scope => resource_name, :recall => "sessions#failure")
      return sign_in_and_redirect(resource_name, resource)
    end

    def sign_in_and_redirect(resource_or_scope, resource=nil)
      scope = Devise::Mapping.find_scope!(resource_or_scope)
      resource ||= resource_or_scope
      sign_in(scope, resource) unless warden.user(scope) == resource
      respond_with do |format|
        format.json  {render :json => {:success => true} }
        format.any  {super}
      end
    end

    def failure
      respond_with do |format|
        format.json  {render:json => {:success => false, :errors => ["Login failed."]} }
        format.any  {redirect_to :back, :notice => "Wrong Email / Password" }
      end
      #return render:json => {:success => false, :errors => ["Login failed."]}
    end

  end

"Rails & Devise: Override SessionsController is more discussion on the same subject.

Community
  • 1
  • 1
maximus ツ
  • 7,949
  • 3
  • 25
  • 54
0

Ended up with creating a new stategy to warden.

On the valid? method i check if the params[:controller] comes from the api namespace. This way I didn't touch the default devise authentication by http.

Community
  • 1
  • 1
dcarneiro
  • 7,060
  • 11
  • 51
  • 74