Skip to content

Instantly share code, notes, and snippets.

@matellis
Created May 3, 2010 06:32
Show Gist options
  • Save matellis/387817 to your computer and use it in GitHub Desktop.
Save matellis/387817 to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
helper :all
protect_from_forgery # See ActionController::RequestForgeryProtection for details
filter_parameter_logging :password, :password_confirmation, :card_number, :cvv, :card_expiry
EXCEPTIONS_NOT_LOGGED = ['ActionController::UnknownAction',
'ActionController::RoutingError']
before_filter {|ct| switch_user ct }
#
# switch_user - detect when a user is attempting to login with a legacy user ID instead of an email address
#
# **** Nasty nasty hack for Devise ****
#
# In the Rails 3 version of Devise you can have custom controllers but not in Rails 2.3
# Choice: either copy the whole sessions controller into the app and do this work here in a filter
#
# Two parts:
#
# (1) For the right session pull out the ID field and see if it's an email address.
# If not, see if we can lookup an email address with this ID
#
# (2) If the password was wrong, switch back the original user ID so people can't
# get email addresses simply by trying the user ID of a customer
#
# In this example I've defined the alternate ID field using a constant (as I don't want to have
# to change Devise in anyway) which also feels 'wrong'. For ease of use I put this constant
# in my devise.rb initializer and it looks like this:
#
# DEVISE_ALT_AUTHENT_KEY = :user_id
#
def self.switch_user(ct)
if defined?(DEVISE_ALT_AUTHENT_KEY) && ct.controller_name == "sessions" && ct.action_name == "create"
resource_name = ct.devise_mapping.name
key = Devise.authentication_keys.first
id = ct.params[resource_name][key]
if id.split("@").length == 1
resource = Object.const_get(resource_name.to_s.classify).find(:first, :conditions => {DEVISE_ALT_AUTHENT_KEY => id})
if !resource.nil?
replacement_id = resource.send(key)
if !replacement_id.nil?
ct.params[resource_name][key] = replacement_id
ct.params[:original_id] = id
end
end
end
# This runs when the user is returned back to sessions/create because
# their password is wrong. We need to hide the switch so folks can't
# figure out the email address for a given user ID.
if ct.current_user.nil? && !ct.params[:original_id].blank?
resource_name = ct.devise_mapping.name
ct.params[resource_name][Devise.authentication_keys.first] = ct.params[:original_id]
end
end
# Nothing to do with the above
Authorization.current_user = ct.current_user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment