Case insensitive name while maintaining capitalization in the project

Using the name as a key, how do we check the name during registration, ignoring case, while maintaining a message about when it is displayed?

In config/initializers/devise.rb setting config.case_insensitive_keys = [ :name ] seems to populate the entire name before registering.

Example: some dudes call themselves TheFourthMusketeer.

  • Views will display TheFourthMusketeer, not fourthmusketeer
  • A new user cannot register under, say tHEfourthMUSKETEER
+4
source share
2 answers

What you can try is not to set :name as case-insensitive, which will correctly store the case-sensitive name in the database:

 config.case_insensitive_keys = [] 

Then override the find_first_by_auth_conditions class find_first_by_auth_conditions for the user to find the user by name. Please note that this code will depend on the database (Postgres is used below):

 def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions).where("lower(name) = ?", login.downcase).first else where(conditions).first end end 

Having done this, User.find_for_authentication(login: 'thefourthmusketeer') will return the entry using name to "TheFourthMusketeer".

See https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address for an explanation of overriding this method.

+6
source

The accepted answer is incomplete because it is still case sensitive when registering. For example, "username" and "USERNAME" can be successfully registered, but only the first can log in.

Disable case-insensitive keys in config/initializers/devise.rb (this may also be model specific, so check there):

 config.case_insensitive_keys = [] 

Overwrite the find_first_by_auth_conditions models/user.rb :

 def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:username) where(conditions).where(["lower(username) = :value", { :value => login.downcase }]).first else where(conditions).first end end 

... and also set validates_uniqueness_of in models/user.rb :

 validates_uniqueness_of :username, :case_sensitive => false 

So, you have this: case-insensitive authentication, case-insensitive registration, which stores the case in the database.

+1
source

All Articles