From c0d01ee05e60c4006f7bb9274ab9006dfc8070fa Mon Sep 17 00:00:00 2001 From: Felix Eckhofer <felix@eckhofer.com> Date: Mon, 23 Dec 2024 13:44:46 +0100 Subject: [PATCH] Allow user to have non-lowercase names Login still works regardless of case! --- app/models/user.rb | 11 +++++++++++ config/initializers/devise.rb | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 989e2c0..b96957d 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -19,6 +19,17 @@ class User < ApplicationRecord after_initialize :set_avatar_color + # Custom method to allow user to sign-in with any case while still storing the "correct" case in the database + def self.find_for_database_authentication(warden_conditions) + conditions = warden_conditions.dup + if (login = conditions.delete(:name)) + where(conditions.to_h).where(["lower(name) = :value", { value: login.downcase }]).first + else + logger.warn("Authentication did not query :name as expected, login will only work with exact case!") + where(conditions.to_h).first + end + end + def errors super.tap { |errors| errors.delete(:password, :blank) if password.nil? } end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index 5bb8a00..64ed76c 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -58,12 +58,12 @@ Devise.setup do |config| # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. - config.case_insensitive_keys = [:name] + config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. - config.strip_whitespace_keys = [:name] + config.strip_whitespace_keys = [:email, :name] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the -- GitLab