CamelWriter CamelWriter - 3 months ago 20
Ruby Question

BCrypt authentication always failing RAILS

I'm following Michael Hartl's Ruby on Rails Tutorial, where I reached Chapter 8. But the authenticated? method always returns false. The Cookie for :remember_token is saved properly. But as i compare the in the database digested remember_digest via

BCrypt::Password.new(remember_digest).is_password?(remember_token)
it will always return false. I'm using Rails 4.2.5.1. Here is my code:

controllers/sessions_controller.rb

class SessionsController < ApplicationController
def new
end

def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in(user)
params[:session][:remember_me] == '1' ? remember(user) : forget(user)
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end

def destroy
log_out if logged_in?
redirect_to root_url
end
end

models/user.rb

class User < ActiveRecord::Base
attr_accessor :remember_token

before_save { email.downcase! }
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, length: { maximum: 250 }, format: { with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i }, uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
has_secure_password

def self.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))
end

def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end

def forget
update_attribute(:remember_digest, nil)
end
end

helpers/sessions_helper.rb

module SessionsHelper
def log_in(user)
session[:user_id] = user.id
end

def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end



def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent.signed[:remember_token] = user.remember_token
end

def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end

def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
@current_user = user
puts "INSIDE"
end
end
end

def logged_in?
!current_user.nil?
end
end

Answer

In helpers/sessions_helper.rb => remember(user) on second line change:

cookies.permanent.signed[:remember_token] = user.remember_token

to:

cookies.permanent[:remember_token] = user.remember_token
Comments