LoginSignup
1
2

More than 5 years have passed since last update.

ユーザー登録<パスワードのハッシュ化>

Posted at
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にはこんな感じで登録される

スクリーンショット 2019-04-03 13.43.29.png

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2