gemfile.
#コメントアウト外す
gem 'bcrypt', '~> 3.1.7'
bundle install
※passwordカラムは作成しない
rails g model User password_hash:string password_salt:string
ファイル作成
models/concerns/user_authenticater.rb
module UserAuthenticator
extend ActiveSupport::Concern
included do
before_save :encrypt_password
attr_accessor :password
end
module ClassMethods
# 認証
def authenticate(email, password)
user = self.approved.readonly(false).find_by_email(email)
if user.present? && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
return user
else
return nil
end
end
end
private
# パスワードソルトを生成、パスワードをハッシュ化し保存
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(self.password, self.password_salt)
end
end
end
適用させたいモデルに追記
user.rb
include UserAuthenticator
attr_accessor :password
ストロングパラメータに :password 記載
でDBにはこんな感じで登録される