wardencommunity/warden

Can't get multiple strategies to work quite right

mustmodify opened this issue · 2 comments

First, just wanted to say thanks for a great, (almost) simple piece of software.

Second: I'm migrating a Rails 3.2 app to greener (higher numbered) pastures. AuthLogic, which served me well forever, apparently doesn't work in 4. The warden.rb file below has been migrated from an app written a few years ago ... but I looked at your docs and it doesn't seem like the basic interface has changed. Feels like it should work.

I have two authentication strategies, httpauth and params. Params works fine.

Started POST "/user_sessions" for 127.0.0.1 at 2016-08-17 16:32:12 -0500
Processing by UserSessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "username"=>"...."}
[AUTH] checking params
[AUTH] Authenticating user jw@mustmodify.com from params
...
[AUTH] User jw@mustmodify.com authenticated with a password.
...
Completed 302 Found in 111.5ms (ActiveRecord: 1.0ms)

However, when using httpauth (via curl):

curl http://dev.projectdomain.com/clouds/bmi.svg -u user:password

I'm expecting to see "checking httpauth" then "checking params" ... but instead I see "checking params" twice. I assume I'm asking warden twice to authenticate... not sure why it appears twice. But according to my understanding, I should also be seeing "checking httpauth". Any thoughts about why that isn't working?

development.log:

Started GET "/clouds/bmi.svg" for 127.0.0.1 at 2016-08-17 16:22:51 -0500
Processing by CloudsController#show as SVG
  Parameters: {"id"=>"bmi"}
[AUTH] checking params
[AUTH] checking params

Here's my config/initializers/warden.rb file:

Rails.application.config.middleware.use Warden::Manager do |manager|
  manager.default_strategies :httpauth, :params
end

Warden::Manager.serialize_into_session do |user|
  user.persistence_token
end

Warden::Manager.serialize_from_session do |id|
  User.where(persistence_token: id).first
end

class UserCredentialAuthentication < ::Warden::Strategies::Base
  def verify_against_old_credentials( user, password )
    Sha512.matches?( user.sha512_password, password, user.sha512_salt )
  end

  def transition_from_sha512!( user, password )
    user.password = password
    user.sha512_password = nil
    user.sha512_salt = nil
    user.save
  end

  def authenticate!
    Rails.logger.warn("[AUTH] Authenticating user #{username} from #{medium}")
    user = User.find_by_username_or_email(username)

    if user.blank?
      Rails.logger.warn("[AUTH] No Such User")
      fail "Invalid email or password"

    elsif user.sha512_password.not.blank? && verify_against_old_credentials( user, password )
      Rails.logger.warn("[AUTH] User #{user.email} authenticated with a SHA512 password.")
      transition_from_sha512!( user, password )
      success! user

    elsif user.password_digest && user.authenticate( password )
      Rails.logger.warn("[AUTH] User #{user.email} authenticated with a password.")
      success! user

    else
      Rails.logger.warn("[AUTH] Bad Password")
      fail "Invalid email or password"

    end
  end
end


Warden::Strategies.add(:httpauth, UserCredentialAuthentication) do
  def medium
    'httpAuth'
  end

  def valid?
    Rails.logger.warn("[AUTH] checking httpAuth")
    auth.provided? && auth.basic?
  end

  def auth
    @auth ||= Rack::Auth::Basic::Request.new(env)
  end

  def username
    auth.credentials[1]
  end

  def password
    auth.credentials[2]
  end
end

Warden::Strategies.add(:params, UserCredentialAuthentication) do
  def medium
    'params'
  end

  def valid?
    Rails.logger.warn("[AUTH] checking params")
    credential_params['username'] && credential_params['password']
  end

  def username
    credential_params['username']
  end

  def password
    credential_params['password']
  end

  def credential_params
    p = params.blank? ? post_params : params
    p['user_session'] || {}
  end

  def post_params
    @post_params ||= get_post_params
  end

  def get_post_params
    req = Rack::Request.new(env)

    if( req.post? )
      begin
        body = req.body.read
        req.body.rewind
        JSON.parse( body )
      end
    else
      {}
    end
  end
end

It seems like Warden ignores more than one strategy with the same parent class. I turned that class into a module and it worked. See final code in StackOverflow.