devise で認証キーを email から username に変更する


はじめに

手元に同志が作った Rails アプリがありましたとさ。
これを流用・シュリンクして別の目的のアプリに改変することにしましたとさ。
認証には devise が利用されていましたとさ。定期。

なんか手元で試したら、ネットで見かける改変手順より全然少なかったので、ちょっと整理しておこうかと思った次第です。

結論

核としては、モデルにフィールドを追加して config/initializers/devise.rbconfig.authentication_keys を変更するだけでした。

diff --git a/db/migrate/20190123123456_add_username_to_users.rb b/db/migrate/20190123123456_add_username_to_users.rb
new file mode 100644
index 0000000..803173d
--- /dev/null
+++ b/db/migrate/20190123123456_add_username_to_users.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddUsernameToUsers < ActiveRecord::Migration[5.2]
+  def change
+    add_column :users, :username, :string, default: '', null: false
+  end
+end
diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb
index 4b5dfa4..7d993f6 100644
--- a/config/initializers/devise.rb
+++ b/config/initializers/devise.rb
@@ -44,7 +44,7 @@ Devise.setup do |config|
   # session. If you need permissions, you should implement that in a before filter.
   # You can also supply a hash where the value is a boolean determining whether
   # or not authentication should be aborted when the value is not present.
-  # config.authentication_keys = [:email]
+  config.authentication_keys = [:username]

   # Configure parameters from the request object used for authentication. Each entry
   # given should be a request method and it will automatically be passed to the
@@ -56,12 +56,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 = [:email]
+  # 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 = [:email]
+  # config.strip_whitespace_keys = [:email]

   # 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

devise には Strong Parameters のデフォルトがある

ここを見ると幾つかの予約語が定義されています。password とか remember_me とか。
そしてここauthentication_keys を参照しています。

これらはユーザーが能動的に指定しなくても Strong Parameters として処理されます。

ところで

この変更をする前に作ったユーザーは、変更後、仮に username を追加できたとしても認証できないです。ご注意を。

おわりに

devise も黒魔術ですね。すごいなぁ。