How could I use authlogic as authentication middleware for a sinatra app specifically split?

StackOverflow https://stackoverflow.com/questions/13433222

  •  30-11-2021
  •  | 
  •  

質問

I am using authlogic in my application. I also have split for A/B testing. I want split to use authlogic for authentication instead the BasicAuthentication or no authentication.

So I set my authentication class as middleware for the split sinatra app:

Split::Dashboard.use SinatraAuthlogic

Then this should be my authlogic middleware for:

class SinatraAuthlogic
  def initialize(app)
    @app = app
  end

  def call(env)
    if is_user_logged_in?
      puts @app.class
      response = @app.call env
    else
      response = Rack::Response.new
      response.redirect '/login'
      response.finish
    end
  end

private

  def is_user_logged_in?
    logged_in = UserSession.find && UserSession.find.user
  end
end

The question is what should I put in the is_user_logged_in in order to work with authlogic?

役に立ちましたか?

解決

After some try I came up with this solution:

class Authlogic::RackAdapter < Authlogic::ControllerAdapters::AbstractAdapter
  def initialize(env)
    request = Rack::Request.new(env)
    super(request)
    Authlogic::Session::Base.controller = self
  end
end

And in my middleware class I modified the 'is_user_logged_in?' method to this one:

def is_user_logged_id?(env)
  begin
    adapter = Authlogic::RackAdapter.new(env)
    logged_in = UserSession.find && UserSession.find.user
    return true
  rescue Exception => e
    return false      
  end
end

This way I can find the user... However when the user isn't logged in instead if nil I got an exception that is why I put the whole code in a rescue block...

Any better aproaches are welcome.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top