diff --git a/app/helpers/sessions_helper.rb b/app/helpers/sessions_helper.rb index 3742569e4..9f59e1c96 100644 --- a/app/helpers/sessions_helper.rb +++ b/app/helpers/sessions_helper.rb @@ -1,10 +1,12 @@ module SessionsHelper def sign_in(user) - cookies.permanent[:remember_token] = user.remember_token + remember_token = User.new_remember_token + cookies.permanent[:remember_token] = remember_token + user.update_attribute(:remember_token, User.encrypt(remember_token)) self.current_user = user end - + def signed_in? !current_user.nil? end @@ -14,13 +16,14 @@ def current_user=(user) end def current_user - @current_user ||= User.find_by(remember_token: cookies[:remember_token]) + remember_token = User.encrypt(cookies[:remember_token]) + @current_user ||= User.find_by(remember_token: remember_token) end def current_user?(user) user == current_user end - + def signed_in_user unless signed_in? store_location diff --git a/app/models/user.rb b/app/models/user.rb index c524ee498..c4cca484e 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -7,7 +7,7 @@ class User < ActiveRecord::Base dependent: :destroy has_many :followers, through: :reverse_relationships, source: :follower before_save { self.email = email.downcase } - before_save :create_remember_token + before_create :create_remember_token validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, @@ -31,9 +31,22 @@ def unfollow!(other_user) relationships.find_by(followed_id: other_user.id).destroy end + def User.new_remember_token + SecureRandom.urlsafe_base64 + end + + def User.encrypt(token) + cost = if ActiveModel::SecurePassword.min_cost + BCrypt::Engine::MIN_COST + else + BCrypt::Engine::DEFAULT_COST + end + BCrypt::Password.create(token, cost: cost) + end + private def create_remember_token - self.remember_token = SecureRandom.urlsafe_base64 + self.remember_token = User.encrypt(User.new_remember_token) end end