0
votes

On my project devise provides user registration/authentication for admin panel. I need to add API method which will sign_in user and return JSON with status + session cookie.

routes.rb

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

Session Controller

class SessionsController < Devise::SessionsController
  skip_before_filter :verify_authenticity_token

  def create
    resource = warden.authenticate!(:scrope => resource_name, :recall => "#{controller_path}#failure")
    sign_in(resource_name, resource)

    respond_to do |format|
      format.html { respond_with resource, :location => after_sign_in_path_for(resource) }
      format.json { render json: {:success => 1}}
    end
  end

If I will post data to user/sign_in.json, it will render {"success": 1} which is exactly that I need.

But the question is how to move user/sign_in.json on some custom url such as /api/sign_in ?

2

2 Answers

0
votes

Surround the route in a namespace:

namespace :api do
  devise_for :user, :controllers => {sessions: 'sessions'}
end
0
votes

Did it like that:

api_controller.rb

def create_session
    resource = User.find_for_database_authentication(:email => params[:user][:email])

    if resource.nil?
      render :json=> {:success => 0, :error => "No Such User"}, :status=>401
    else
      if resource.valid_password?(params[:user][:password])
        sign_in(:user, resource)
        render :json=> {:success => 1}
      else
        render :json=> {:success => 0, :error => "Wrong Password"}, :status=>401
      end
    end 
  end

routes.rb

namespace :api do
    namespace :v1 do
      get :sign_in, :to => 'api#create_session'
    end
  end