あり得ない実装だけれども、応用のためのメモ。参考にさせて頂いたサイト
rails:5.0.0
ruby:2.2.4p230
- devise-encryptableのインストール
- Userモデルへencryptableモジュールの追加
- password_saltを追加するためのマイグレーション
- 暗号化のカスタマイズ
- seedでUser.create時の注意
devise-encryptableのインストール
Gemfileへ以下を追記し、bundle installを行う。
gem "devise-encryptable"
Userモデルへencryptableモジュールの追加
:encryptableを追記する。
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :encryptable, :recoverable, :rememberable, :trackable, :validatable end
password_saltを追加するためのマイグレーション
devise-encryptableを利用するにはUsersテーブルにpassword_saltのカラムが必要となるのでマイグレーションで追加する。
rails g migration AddPasswordSaltToUsers password_salt:string
マイグレーションファイルを編集する。(カラムの追加場所を:afterで指定しただけ)
class AddPasswordSaltToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :password_salt, :string, :after => :encrypted_password end end
マイグレーションを実行する。
rails db:migrate
暗号化のカスタマイズ
config/initializers/devise_encryptor.rbを作成する。暗号化しないのでdigestとcompareをpasswordそのまま使うようにカスタマイズ。
module Devise module Encryptable module Encryptors class PasswordAuthentification < Base def self.digest(password, stretches, salt, pepper) password end def self.salt(stretches) end def self.compare(encrypted_password, password, stretches, salt, pepper) encrypted_password == password end end end end end
config/initializers/devise.rbを編集する。
# config.encryptor = :sha512 config.encryptor = :password_authentification
seedでUser.create時の注意
初期データ作成のためにseedで以下のようにしていた場合、
User.create!(password: 'pass', password_confirmation: 'pass', uid: 'test', name: 'testuser')
このようにしたら登録出来た。
User.create!(password: 'pass', encrypted_password: 'pass', uid: 'test', name: 'testuser')