1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【rails】use.ymlでencrypted_passwordをハッシュ化する方法

Posted at

はじめに

こんにちは。アメリカ在住で、独学でエンジニアを目指している Taira です。
現在 Rails アプリを devise を用いて作成しています。
test/fixtures/user.yml に user を設定してテストに使用することがよくあります。

user1:
  name: takeshi
  email: test1@example.com
  encrypted_password: '何を書けばいい?'
  confirmed_at: <%= Time.current %>

このとき、encrypted_passwordにパスワードを設定したいのですが、devise は内部でどのようにハッシュ化しているのかわかりにくい、という問題にぶつかりました。
そこで今回は、encrypted_passwordの値をどう設定すればよいか、devise のハッシュ化処理のソースコードを読み解くことで解説します。

encrypted_passwordのハッシュ化方法

https://github.com/heartcombo/devise

上記リポジトリの devise/lib/devise/encryptor.rb の 7 行目に該当の処理があります。

module Devise
  module Encryptor
    def self.digest(klass, password)
      if klass.pepper.present?
        password = "#{password}#{klass.pepper}"
      end
      ::BCrypt::Password.create(password, cost: klass.stretches).to_s
    end
    # ...(省略)
  end
end

digestクラスメソッドは、第一引数にクラス(ここでは User)、第二引数にパスワードを渡して呼び出すことで、devise が期待する形式でハッシュ化できます。

つまり、fixture の user.ymlencrypted_password を指定するには、以下のように書くことができます。

user.yml
user1:
  name: takeshi
  email: test1@example.com
  encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>
  confirmed_at: <%= Time.current %>

まとめ

ハッシュ化の方法をソースコードから探すアプローチは、Rails チュートリアルでも学習した大切な方法です。
今後も困ったときには積極的にソースコードを読む姿勢を大事にしたいと思います。

参考資料

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?