John Bachir
John Bachir

Reputation: 22741

Configuring Devise to treat email addresses case-insensitively in all circumstances?

I recently found that if I have an email address saved in the db as "[email protected]", Devise won't allow signing in with "[email protected]" OR "[email protected]". I believe this is because devise downcases input before comparing. It assumes that all the data will be downcasesed in the databsae, but some of my data is created with external scripts and doesn't get run through Devise.

There are a few related questions and things on the web addressing this, but they are somewhat old discussions and/or the solutions seem hacky or elaborate. I'd rather not overwrite any finder methods.

Is there an official or otherwise elegant way to configure devise to treat everything case-insensitively?

Upvotes: 1

Views: 55

Answers (2)

ninesided
ninesided

Reputation: 23273

If you can't update your external scripts to downcase email addresses, you could always add a trigger to the table in the database to do it for all inserts/updates:

CREATE FUNCTION user_upsert() RETURNS trigger AS $user_upsert$
BEGIN
    NEW.email_address := LOWER(NEW.email_address);
    RETURN NEW;
END;
$user_upsert$ LANGUAGE plpgsql;

CREATE TRIGGER user_upsert BEFORE INSERT OR UPDATE ON user
FOR EACH ROW EXECUTE PROCEDURE user_upsert();

Upvotes: 1

OneChillDude
OneChillDude

Reputation: 8006

Well, one option you have is to override the devise session controller. For example you could create a file in app/controllers/sessions_controller.rb

class SessionsController < Devise::SessionsController
  def create
    @user = User.where('email IS LIKE ?', params[:user][:email])
    sign_in @user if @user.valid_password?(params[:user][:password])            
  end
end

Upvotes: 0

Related Questions