Updating a User model resets password? Rails question - ruby-on-rails

In my controller, I try updating a user instance's rank attribute (integer). For example from 1 to 2.
I do this by:
#user = User.find(params[:id])
#user.rank = 2
#user.save(:validate => false)
For some reason the password for the user being saved gets erased, so that they can log in to my site without a password at all. I've tried with and without the :validate => false parameter.
Any reason why? help? Thanks a bunch
Model Code
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :login, :email, :fname, :lname, :password, :password_confirmation, :rank, :hours, :wars
email_filter = /\A[\w+-.]+#[a-z\d-.]+.[a-z]+\z/i
validates :login, :presence => true, :length => { :maximum => 15, :minimum => 4 }, :uniqueness => true
validates :fname, :presence => true, :length => {:minimum => 2 }
validates :lname, :presence => true, :length => {:minimum => 2 }
validates :email, :presence => true, :format => { :with => email_filter}, :uniqueness => { :case_sensitive => false }
validates :password, :presence => true, :confirmation => true, :length => { :within =>4..40 }
validates :lane_id, :presence => true
before_save :encrypt_password
has_many :reports
has_many :accomplishments
belongs_to :lane
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(login, submitted_password)
user = find_by_login(login)
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
def current_report
report = (Report.order("created_at DESC")).find_by_user_id(#user.id)
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

You only want to encrypt the password if one is present, so add a condition to your callback
before_save :encrypt_password, :unless => "password.blank?"
Also, you do not want to validate the password every time you update the user record. You can remove the :presence => true validation, and add a condition to run the other validations only when the password is present.
validates :password, :confirmation => true, :length => { :within =>4..40 }, :unless => "password.blank?"

You have a before_filter that encrypts the password everytime you save your model. Instead of a before_filter use something like this:
def password=(new_password)
self.salt = make_salt if new_record?
self.encrypted_password = encrypt(new_password)
end

I know this is severely late, but I actually just stumbled across this article on therailsways.com that was written back in 2009, but still worked for me in case anyone else who comes here through Google might have this same problem.
before_save :encrypt_password, :if => :password_changed?
I was having the same problem where my password would be re-encrypted on update, but I only wanted to encrypt it on user creation.
I was looking for alternatives to before_save, but none of them really did the trick. This however, certainly did, and all I had to do was add that if condition. It worked perfectly.

Related

Rails, update method and validation

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

Rails - Submitting Nested Values That Already Exist

I have a model, Tran that has a foreign key to the User model. In the view for creation a Tran (transaction), I have a dropdown that allows the user to select the User that started the transaction. When I post this transaction, the record is set with the correct user ID:
Then, in my Trans model I added "belongs_to", as I understand I should do this for foreign keys:
class Tran < ActiveRecord::Base
belongs_to :buying_user, :class_name => 'User'
Now, when my client passes up the params in the post, my Tran.new craps out because I am passing up a userID and not a full record. Is the
#trans_controller.rb
def create
#title = "Create Transaction"
#bombs on this call
#tran = Tran.new(params[:tran])
How am I supposed to handle this?
Update as requested:
tran.rb
class Tran < ActiveRecord::Base
has_many :transaction_users, :dependent => :destroy, :class_name => 'TransactionUser'
belongs_to :submitting_user, :class_name => 'User'
belongs_to :buying_user, :class_name => 'User'
accepts_nested_attributes_for :transaction_users, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
validates :description, :presence => true,
:length => {:maximum => 100 }
validates :total, :presence => true
validates_numericality_of :total, :greater_than => 0
validates :submitting_user, :presence => true
validates :buying_user, :presence => true
validates_associated :transaction_users
end
user.rb
class User < ActiveRecord::Base
has_many :trans
attr_accessor :password
attr_accessible :firstname, :lastname, :email, :password, :password_confirmation
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :firstname, :presence => true,
:length => {:maximum => 50 }
validates :lastname, :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 }
# Register callback to before save so that we can call extra code like password encryption
before_save :encrypt_password
# Class methods
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
# Public methods
def has_password?(submitted_password)
self.encrypted_password == encrypt(submitted_password)
end
def full_name
"#{self.lastname}, #{self.firstname}"
end
def self.active_users
# TODO
#User.find_
User.all
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
params hash on submit:
{"commit"=>"Submit",
"tran"=>{"total"=>"100",
"submitting_user"=>"1",
"description"=>"Description"},
"authenticity_token"=>"88qI+iqF92fo/M9rPfMs1CLpEXqFLGQXfj0c9krXXac=",
"utf8"=>"✓",
"user"=>"1"}
error:
User(#70040336455300) expected, got String(#70040382612480)
beginning of controller:
def create
#title = "Create Transaction"
#tran = Tran.new(params[:tran])
It crashes on the Tran.new line. Thanks so much!
Typically the User model would have has_many :transactions, :class_name => Tran
Then you would do this...
#user.transaction_create(params[:tran])
or
#user.build
it depends on what parameters are actually passed in params[:tran], but the idea is that the has_many side does the creating of the belongs_to.
I figured it out! The problem the whole time was that my db column name on my Trans table that linked to my Users table was submitting_user instead of submitting_user_id. Then, when I added the belongs_to association to submitting_user rails got confused and made that field a User, instead of an integer.

Adding Rails model attribute results in RecordNotSaved errors

I am extrapolating from a User model given in the Rails tutorial found here to learn more about creating models. I am trying to give a user a confirmation flag, which is initially set false until the user confirms their identity through clicking a link in an automated email sent after registration.
Everything worked before I added the confirmed attribute. I have added a confirmed column to the database through a migration, so it seems to me the error happens somewhere in the before_save :confirmed_false logic.
Can someone help me? The user model is below.
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
before_save :confirmed_false
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
private
def confirmed_false
self.confirmed = false if new_record?
end
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
1,1 Top
In your migration, if you set the confirmed column to be a boolean and the default value to be false then you don't need the before_save :confirmed_false callback at all as it will always be false when it's a new record.
Updated
class User < ActiveRecord::Base
# unlike before_save it's only run once (on creation)
before_create :set_registration_date
def set_registration_date
registration_date = Time.now # or Date.today
end
end
Can't really figure out what you're trying to do here. It seems like you want to set the default to be confirmed = false, then change it to confirmed = true if the user clicks on the appropriate link and sends you the correct token, or something like that.
So the flow would be something like this:
A user record is created with confirmed = false
There is no need for a before_filter do do anything yet
A user does some action that permits his confirmed column to be set to true
Still no need for a before_filter
What's the before_filter for? Are you trying to use it to set a default?

Rails Validates Prevents Save

I have a user model like this:
class User < ActiveRecord::Base
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
.
.
.
end
In the User model, I have a billing_id column I want to save into from a OrdersController which looks like this:
class OrdersController < ApplicationController
.
.
.
def create
#order = Order.new(params[:order])
if #order.save
if #order.purchase
response = GATEWAY.store(credit_card, options)
result = response.params['billingid']
#thisuser = User.find(current_user)
#thisuser.billing_id = result
if #thisuser.save
redirect_to(root_url), :notice => 'billing id saved')
else
redirect_to(root_url), :notice => #thisuser.errors)
end
end
end
end
Because of validates :password in the User model, #thisuser.save doesn't save. However, once I comment out the validation, #thisuser.save returns true. This is an unfamiliar territory for me because I thought this validation only worked when creating a new User. Can someone tell me if validates :password is supposed to kick in each time I try to save in User model? Thanks
You need to specify when you want to run your validations otherwise they will be run on every save call. This is easy to limit, though:
validates :password,
:presence => true,
:confirmation => true,
:length => { :within => 6..40 },
:on => :create
An alternative is to have this validation trigger conditionally:
validates :password,
:presence => true,
:confirmation => true,
:length => { :within => 6..40 },
:if => :password_required?
You define a method that indicates if a password is required before this model can be considered valid:
class User < ActiveRecord::Base
def password_required?
# Validation required if this is a new record or the password is being
# updated.
self.new_record? or self.password?
end
end
It's likely because you are validating that the password has been confirmed (:confirmation => true), but the password_confirmation does not exist.
You can break this out to something like:
validates_presence_of :password, :length => { :within => 6..40 }
validates_presence_of :password_confirmation, :if => :password_changed?
I like this approach because if the user ever changes their password, it will require the user entered the same password_confirmation.

ArgumentError in Chapter 7 of "Rails Tutorial" by Michael Hartl

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

Resources