Good day! I'm practising materials from "Ruby on Rails Tutorial" by Michael Hartle.
Below is the failure message I received, even though the "expected" and "got" seems to match. Would you please give me some suggestion to see how I should approach this issue?
Thank you so much!
Below is the implementation code:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :emp_id, :dept_id, :password, :password_confirmation
validates :emp_id, :presence => true
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
before_save :encrypt_password
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(emp_id, submitted_password)
user = find_by_emp_id(emp_id)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
private
def encrypt_password
self.salt = make_salt if new_record?
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
end
Below is the SPEC code:
require 'spec_helper'
describe User do
before(:each) do
#attr = {:name=>"Example", :dept_id=>01, :emp_id=>10, :password=>"pwdabcd", :password_confirmation => "pwdabcd" }
end
.
.
.
describe "password encryption" do
before(:each) do
#user = User.create!(#attr)
end
.
.
.
describe "authenticate method" do
it "should return the user on emp_id password match" do
matching_user = User.authenticate(#attr[:emp_id], #attr[:password])
matching_user.should == #user
end
end
end
end
Thank you so much for your kind assistance.
Have a nice day!
Kevin - when you see a failure message like that, the representation of the object (#<User ...>) is up to the object, so it's possible that it doesn't show you everything that is being compared by ==. My guess is it has something to do with :password_confirmation, but I'm not certain. It doesn't look like the implementation is using it yet, so try removing password_confirmation from #attr in the spec, and from the attr_accessible declaration, and see if it passes.
Related
I'm new to rails (and ruby in general), so my problem is probably easy to solve. I'm trying to create a simple app where you can create a user and log in. I'm encrypting the password with BCrypt and when i try to log in i get this error: BCrypt::Errors::InvalidSalt in SessionsController#login_attempt
Not sure what files i need to share to solve the problem, so i'll start by sharing the files where it says the error occours.
user.rb
class User < ActiveRecord::Base
before_save :encrypt_password
after_save :clear_password
attr_accessor :password
attr_accessible :username, :email, :password, :password_confirmation
EMAIL_REGEX = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}$/i
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true #password_confirmation attr
validates_length_of :password, :in => 6..20, :on => :create
def encrypt_password
if :password.present?
self.salt = BCrypt::Engine.generate_salt
self.encrypted_password= BCrypt::Engine.hash_secret(:password, :salt)
end
end
def clear_password
self.password = nil
end
def self.authenticate(username_or_email="", login_password="")
if EMAIL_REGEX.match(username_or_email)
user = User.find_by_email(username_or_email)
else
user = User.find_by_username(username_or_email)
end
if user && user.match_password(login_password)
return user
else
return false
end
end
def match_password(login_password="")
encrypted_password == BCrypt::Engine.hash_secret(login_password, salt)
end
end
session_controller.rb
class SessionsController < ApplicationController
before_filter :authenticate_user, :only => [:home, :profile, :setting]
before_filter :save_login_state, :only => [:login, :login_attempt]
def login
#Login Form
end
def login_attempt
authorized_user = User.authenticate(params[:username_or_email],params[:login_password])
if authorized_user
flash[:notice] = "Wow Welcome again, you logged in as #{authorized_user.username}"
redirect_to(:action => 'home')
else
flash[:notice] = "Invalid Username or Password"
flash[:color]= "invalid"
render "login"
end
end
def home
end
def profile
end
def setting
end
def logout
session[:user_id] = nil
redirect_to :action => 'login'
end
end
I followed a tutorial to get this far, so if you can please explain the error too.
Thanks!
Is not necessary to have a salt field in the db, with the encrypted password should be enough. If you use BCrypt::Password instead of BCrypt::Engine you could save both the salt and enc_pasword in the same field. Try to change these methods in user.rb
def encrypt_password
self.encrypted_password = BCrypt::Password.create(password) if password.present?
end
def match_password(login_password="")
BCrypt::Password.new(password) == login_password
end
I am working my through Hartl's Rails Tutorial. I have gotten up to chapter 7, but one of my RSpec test cases is failing, specifically the one dealing with passwords that do not match:
describe "has_password? method" do
it "should be true if the passwords match" do
#user.has_password?(#attr[:password]).should be_true
end
it "should be false if the passwords don't match" do
#user.has_password?("invalid").should be_false
end
end
Output from Terminal:
Failures:
1) User password encryption has_password? method should be false if the passwords don't match
Failure/Error: #user.has_password?("invalid").should be_false
expected "273725daa81e74764ea1e941a0789da7d580656cd321c64e39d1389f6a7e14d9" to be false
# ./spec/models/user_spec.rb:111
Here is my /user.rb code:
require 'digest'
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40}
before_save :encrypt_password
def has_password? (submitted_password)
encrypted_password = encrypt(submitted_password)
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
end
I can't seem to figure out what is wrong for the life of me. I appreciate the help!
In your has_password? method
encrypted_password = encrypt(submitted_password) needs to read:
encrypted_password == encrypt(submitted_password)
I have a problem and I need an idea how to fix my update method. I have an admin panel where I can create users. This form include name, mail, password, repeated password fields and it works fine. Then I want to have a list of all users and to edit these who I want. The problem is that I want to edit part of the information which is not included in the form of the registration and default is empty. In edit mode my form has two new fields - notes and absences. When I change these fields and call update method I see message that password and repeated password don't match which is validation in the registration but I do not have these files in edit mode. How could I fix this problem. This is part of my code:
class UsersController < ApplicationController
def edit
#user = User.find(params[:id])
#title = "Edit user"
end
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated."
redirect_to #user
else
#title = "Edit user"
render 'edit'
end
end
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => true
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
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)
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
end
The validation for password presence is true when you are creating a user, but once a user has an encrypted password, you don't want to force it to be present in all form submissions in the future.
Active record supports adding conditions to validations, so I would suggest putting a condition on the password validation to make it only execute if the user object does not already have an encrypted password. The relevant snippet would be:
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 },
:if => :needs_password?
def needs_password?
encrypted_password.nil?
end
My User model has an attribute called "points" and when I try to update it in another model controller (decrementing points), the attribute will not save (even after adding it to attr_accessible).
The method in my Venture Controller code:
def upvote
#venture = Venture.find(params[:id])
if current_user.points < UPVOTE_AMOUNT
flash[:error] = "Not enough points!"
else
flash[:success] = "Vote submitted!"
current_user.vote_for(#venture)
decremented = current_user.points - UPVOTE_AMOUNT
current_user.points = decremented
current_user.save
redirect_to :back
end
I have even tried using the update_attributes method, but to no avail.
I added a quick little test with flash to see if it was saving:
if current_user.save
flash[:success] = "Yay"
else
flash[:error] = "No"
end
and the error was returned.
current_user comes from my Sessions helper:
def current_user
#current_user ||= user_from_remember_token
end
Thanks ahead of time.
My User model:
class User < ActiveRecord::Base
attr_accessor :password, :points
attr_accessible :name, :email, :password, :password_confirmation, :points
STARTING_POINTS = 50
acts_as_voter
has_karma :ventures
has_many :ventures, :dependent => :destroy
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
before_save :encrypt_password
after_initialize :initialize_points
def has_password?(submitted_password)
password_digest == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
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 initialize_points
self.points = STARTING_POINTS
end
def encrypt_password
self.salt = make_salt if new_record?
self.password_digest = 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
end
This is what I get after printing <%= debug current_user %>
--- !ruby/object:User
attributes:
id: 1
name: Test User
email: a#s.com
created_at: 2011-08-27 21:03:01.391918
updated_at: 2011-08-27 21:03:01.418370
password_digest: 40d5ed415df384adaa5182a5fe59964625f9e65a688bb3cc9e30b4eef2a0614b
salt: ac7a332f5d63bc6ad0f61ceacb66bc154e1cad1164fcaed6189d8cea2b55ffe4
admin: t
points: 50
longitude_user:
latitude_user:
attributes_cache: {}
changed_attributes: {}
destroyed: false
errors: !omap []
marked_for_destruction: false
new_record: false
points: 50
previously_changed: {}
readonly: false
You are requiring the user's password to be present any time the user is saved. When the upvote is submitting, the password is not present, therefor validation is not passing.
This would suggest some kind of validation failed. An easy way to circumvent this, is to use update_attribute. This will update a single attribute and save without running the validations.
So instead write
current_user.update_attribute :points, current_user.points - UPVOTE_AMOUNT
This should work.
This does not solve the problem why saving an existing user could fail, so you still need to check your validations and before_save actions.
Hope this helps.
Ha. Indeed. The update_attribute does skip validations, but not the before_save.
So, if the before_save is the problem, you only want to trigger if the password has changed, so you could do something like
def encrypt_password
self.salt = make_salt if new_record?
self.password_digest = encrypt(password) if self.password_changed?
end
But this would only work if password is an actual attribute of your model, which seems unlikely. Why would you store the hash (for safety reasons) and the password in cleartext. So ... I guess you only have a password_digest field, and then it should become something like:
def encrypt_password
self.salt = make_salt if new_record?
self.password_digest = encrypt(password) if password.present?
end
Only if a password was given, try to recreate the digest.
everyone. I've got the following problem:
After implementing has_password? in section 7.2.3 RSpec displays the following error for "should create a new instance given valid attributes" test for example
1) User should create a new instance given valid attributes
Failure/Error: User.create!(#attr)
ArgumentError:
wrong number of arguments (1 for 0)
# ./app/models/user.rb:42:in secure_hash'
# ./app/models/user.rb:39:inmake_salt'
# ./app/models/user.rb:30:in encrypt_password'
# ./spec/models/user_spec.rb:14:inblock (2 levels) in '
Finished in 1.47 seconds
1 example, 1 failure
<-- Slave(1) run done!
I don't understand, what exactly causes the problem.
Here is my user.rb code:
require 'digest'
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
# Automatically create the virtual attribute "password_confirmation"
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
before_save :encrypt_password
# Return 'true' if the user's password matches the submitted password
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
private
def encrypt_password
self.salt = make_salt if new_record?
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
Digest::SHA2.hexdigest(string)
end
end
What can it be?
Thank you in advance!
Your secure_hash method needs to take an argument.
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end