0

Given I'm on Rails 3.1, Ruby 1.9.2 with a standard setup for devise to log a user in by name and password (e.g. similar to https://github.com/RailsApps/rails3-devise-rspec-cucumber ):

I need to add a layer that authenticates a posted username and password against an external service before creating a new user (sign up) or when a user signs in.

(FWIW, further down the road I plan on using the https://github.com/chicks/devise_aes_encryptable strategy/gem to encrypt the sensitive password and, when logging in with a local password, decrypt the one for the remote service, authenticate, then continue with logging in, that is have two passwords, one encrypted one-way, the other reversible... don't ask why, anyway)

In lib/util/authenticate.rb I have an authentication class that returns a boolean against this service e.g.

Util::Authenticate.authenticate(username,password)

But, I can't figure out how to add a filter to authenticate against it on form post before authentication continues (for sign up or sign in).

What I've tried:

I haver a User model and I thought to put a

before_filter :authenticate_against_my_service, :only => [:create, :new] 

in the UserController but that didn't work

So, I tried opening up the Devise Sessions controller, which didn't work, nor did subclassing it (e.g. in the README ),

class User::SessionsController < Devise::SessionsController
  # something
end

# in config/routes.rb
devise_for :users, :controllers => { :sessions => "users/sessions" }

nor subclassing the Devise Registrations controller (e.g. http://www.tonyamoyal.com/2010/07/28/rails-authentication-with-devise-and-cancan-customizing-devise-controllers/ )and adding a before_filter (same as above).

# in app/controllers/users/registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  before_filter :check_permissions, :only => [:new, :create, :cancel]
  skip_before_filter :require_no_authentication

  def check_permissions
    authorize! :create, resource
  end
end

# and in config/routes.rb 
root :to => "home#index"
#  replace "devise_for :users" with the below
devise_for :users,  :controllers => { :registrations => "users/registrations" }
# other related code
devise_for :users do 
  get 'logout' => 'devise/sessions#destroy' 
end
# resources :users, :only => :show MUST be below devise_for :users
resources :users, :only => :show

I think I have to do this in the controller because once the params get to the model, I won't have an unencrypted password to send to the external service.

I looked at some extensions for ideas such as https://raw.github.com/nbudin/devise_cas_authenticatable/master/lib/devise_cas_authenticatable/strategy.rb e.g.

require 'devise/strategies/base'

module Devise
  module Strategies
    class CasAuthenticatable < Base
      # True if the mapping supports authenticate_with_cas_ticket.
      def valid?
        mapping.to.respond_to?(:authenticate_with_cas_ticket) && params[:ticket]
      end

      # Try to authenticate a user using the CAS ticket passed in params.
      # If the ticket is valid and the model's authenticate_with_cas_ticket method
      # returns a user, then return success.  If the ticket is invalid, then either
      # fail (if we're just returning from the CAS server, based on the referrer)
      # or attempt to redirect to the CAS server's login URL.
      def authenticate!
        ticket = read_ticket(params)
        if ticket
          if resource = mapping.to.authenticate_with_cas_ticket(ticket)
            # Store the ticket in the session for later usage
            if ::Devise.cas_enable_single_sign_out
              session['cas_last_valid_ticket'] = ticket.ticket
              session['cas_last_valid_ticket_store'] = true
            end

            success!(resource)
          elsif ticket.is_valid?
            username = ticket.respond_to?(:user) ? ticket.user : ticket.response.user
            redirect!(::Devise.cas_unregistered_url(request.url, mapping), :username => username)
            #fail!("The user #{ticket.response.user} is not registered with this site.  Please use a different account.")
          else
            fail!(:invalid)
          end
        else
          fail!(:invalid)
        end
      end
      protected

      def read_ticket(params)
        #snip
      end
    end
  end
end

Warden::Strategies.add(:cas_authenticatable, Devise::Strategies::CasAuthenticatable)

and read about devise/warden authentication strategies, e.g. https://github.com/hassox/warden/wiki/Strategies but wonder if I need to actually create a new strategy (and if I can figure out how to do that)

EDIT, POSSIBLE SOLUTIONS:

I like alno's suggestion and will try that, though it seems more like a monkeypatch than how devise/warden is meant to be used

module Devise::Models::DatabaseAuthenticatable
  alias_method :original_valid_password?, :valid_password?
  def valid_password?
    if Util::Authenticate.authenticate(username,password)
      original_valid_password?
    else
      false
    end
  end
end

alternatively, I've looked into adding a warden authentication strategy, but it's hard to figure out all the moving parts, e.g. from Custom authentication strategy for devise

initializers/authentication_strategy.rb: # this could be in initializers/devise.rb as well, no?

Warden::Strategies.add(:custom_external_authentication) do 
  def valid? 
    # code here to check whether to try and authenticate using this strategy; 
    return true # always use the strategy as only user's authenticate
  end 

  def authenticate! 
    # code here for doing authentication; if successful, call success! 
    # whatever you've authenticated, e.g. user; if fail, call fail! 
    if Util::Authenticate.authenticate(username, password)
      success!(true) # I don't think I want to return a user, as I'll let database authenticatable handle the rest of the authentication
      # I don't think I'm using success! correctly here: https://github.com/hassox/warden/wiki/Strategies
      # success!(User.find(someid))
    else
      fail!("Username and password not valid for external service. Please ensure they are valid and try again.")
    end
  end 
end 

add following to initializers/devise.rb

Devise.setup do |config|
  config.warden do |manager| 
    manager.default_strategies.unshift :custom_external_authentication # will this check before or after database authentication? I want before, I think
  end 
end

OR from How do I add a strategy to Devise

class ExternalServiceStrategy
  def valid?
    true # always use this
  end

  def authenticate!
    # external boolean service call
  end
end

Warden::Strategies.add(:database_authenticatable, ExternalServiceStrategy) # will this work before the db authentication?

2 Answers 2

1

If you see in devise source, you will find an valid_password? method, which accepts unencrypted password, so you may override it to authenticate versus some extenal service.

Something like:

def valid_password?(password)
  ExternalService.authenticate(email, password)
end
1
  • Look interesting, will try module Devise::Models::DatabaseAuthenticatable alias_method :original_valid_password?, :valid_password? def valid_password? if Util::Authenticate.authenticate(username,password) original_valid_password? else false end end end
    – BF4
    Nov 10, 2011 at 15:57
0

You should be making your changes in the model layer, not in the controller. In fact I would advice you create a file in /lib/whatever that handles talking to the external service, and then modify your User model so that it checks the external service.

3
  • I apologize for not yet having added code examples. Yes, I wrote a utility in lib/util/authenticate.rb that does the authentication e.g. Util::Authenticate.authenticate(username,password). Two problems with using the model as I see it 1) a validation would only apply on user creation or update, and would need access to the unencrypted password, (which it can't have, right?), and 2) I need to auth against the service on sign in of an existing user as well, to confirm the 3rd party auth is still valid (though ideally I could use the stored 3rd party password)
    – BF4
    Nov 10, 2011 at 15:55
  • It is still absolutely the case that the right place for your code is in the model. If there are challenges associated with that then I'd suggest a new question.
    – thomasfedb
    Nov 13, 2011 at 13:24
  • Ok, I think I see how I could do it, the controller, which has access to the form data, can call a method on the model. I could certainly use that approach, which I suppose is related to the modification of Devise::Models::DatabaseAuthenticatable as suggested by alno, as the model calls the macro :database_authenticatable
    – BF4
    Nov 16, 2011 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.