5

I'm trying to build an API for login using GrapeAPI and Authlogic.

My code looks like this:

class Api
  class V1
    class UserSessionsController < Grape::API


    post :login do
      @user_session = UserSession.new(params[:user_session])
      if @user_session.save
        fetch_api_key(@user_session.user)
      else
        error!('Unauthorized.', 401)
      end
    end

    helpers do
      def current_user_session
        return @current_user_session if defined?(@current_user_session)
        @current_user_session = UserSession.find
      end

      def current_user
        return @current_user if defined?(@current_user)
        @current_user = current_user_session && current_user_session.user
       end

      end

    end
  end
end

The problem is that when I run @user_session = UserSession.new(params[:user_session]) I get You must activate the Authlogic::Session::Base.controller with a controller object before creating objects.

I tried adding

Authlogic::Session::Base.controller = Authlogic::ControllerAdapters::RailsAdapter.new(self)

before trying to create the UserSession and now I get undefined method 'session' for #<#<Class:0x007fa7a63ade28>:0x007fa7a7b144b8> when I run @user_session.save.

PS: I also tried adding authenticate_with User to the user_session.rb file, and

acts_as_authentic do |c| c.session_class = UserSession end

Inside the user model, but it doesn't work.

PS2: I'm using rails 4,2,7 , grape 0.18.0 and authlogic 3.4.6

Florin Ionce
  • 855
  • 7
  • 15
  • Have you looked at [the authentication section of grape's docs](https://github.com/ruby-grape/grape#authentication)? There's a section there on "Register custom middleware for authentication". Also, it might help to research [how people have integrated other authentication libraries, like devise](https://stackoverflow.com/questions/26623980/user-authentication-with-grape-and-devise). – Jared Beck Feb 02 '17 at 23:06
  • Does your UserSession model inherit from Authligic, rather than ActiveRecord? – Dan Laffan Feb 05 '17 at 23:59
  • Sorry for my late reply. @DanLaffan My model inherits from AuthLogic. @JaredBeck I've looked at this, but I think the problem is in AuthLogic since the logic for rails apps is based on controllers which are subclasses of `ApplicationController` and with grape they are behaving differently. – Florin Ionce Feb 06 '17 at 07:33
  • Taking your point in reply to Jared, I wonder if AuthLogic would ever work for you? Perhaps you could check out the RSpec/TestUnit support that AuthLogic offers. Not sure if this idea would be of any real value to you though. – Dan Laffan Feb 06 '17 at 20:53

0 Answers0