(ruby 1.9.2, rails 3.1) Following Michael Hartl’s tutorial. Spent more than a day trying to figure out the issue, re-read the chapter, browsed SO, no solution so far.
When I create users they are all created with nil in salt field in DB. Like that:
=> #<User id: 19, name: "John Doe Fourth", email: "jdoe4@ibm.com", created_at: "2011-12-10 16:36:09", updated_at: "2011-
12-10 16:36:09", encrypted_password: "5534438b422e928e80479756608b87d33881b5196a28be230c2...", salt: nil>
This (imho) the reason I get “invalid user/email combination” when I try to login.
Any pointers would be much appreciated.
Here is the info that you might need, hope it’s not too much.
users_controller.rb
def new
@user = User.new
@title = "Sign up"
end
def create
@user = User.new(params[:user])
if @user.save
sign_in @user
flash[:success] = "Welcome to the Blue Bird Microblog!"
redirect_to @user
else
@title = "Sign up"
render 'new'
end
end
user.rb
require 'digest' class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
attr_accessor :password, :salt
before_save :encrypt_password
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
puts user.inspect
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
def self.authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt) ? user : nil
end
private
def encrypt_password
self.salt = make_salt unless has_password?(password)
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
You need to remove
attr_accessor is for instance variables, and since salt is in the database; you need to get rid of that accessor line for it.