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

More than 3 years have passed since last update.

Railsチュートリアル9章の解読メモ

Last updated at Posted at 2019-12-17

class User < ApplicationRecord
attr_accessor :remember_token #仮想の属性 remember_tokenを作る
.
.
.

渡された文字列のハッシュ値を返す

def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end

ランダムなトークンを返す

def User.new_token
SecureRandom.urlsafe_base64
end

永続セッションのためにユーザーをデータベースに記憶する

def remember
self.remember_token = User.new_token #リメンバートークンに ランダムなトークンを入れる
update_attribute(:remember_digest, User.digest(remember_token)) #実のあるremember_digestにremember_tokenをハッシュ値にしたものを突っ込む
end
end

cookies[:user_id] = user.id
cookies.signed[:user_id] = user.id #署名付きcookieにする
cookies.permanent.signed[:user_id] = user.id #恒久的になるパーマネントビザ的な
User.find_by(id: cookies.signed[:user_id]) #これでユーザーが取り出せる。cookies.signedで暗号化を解除

BCrypt::Password.new(remember_digest) == remember_token #これ使う。暗号化パスとトークンの直接比較

bcryptの機能で == が .is_password? になる。

BCrypt::Password.new(remember_digest).is_password?(remember_token) #渡されたトークンとユーザーの記憶ダイジェストを突き合わせ

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