Fixing a Blank Password Bug in Acts As Authenticated

I came across a bug in Acts As Authenticated when users tried to change their passwords. If they submitted the form with nothing in the new or confirm new password text field, then no error was thrown, but the password wasn't changed either.

The problem was in the :if clause on the validates_presence_of validation, password_required?. It was causing the validation not to occur.

    def password_required?
crypted_password.blank? || !password.blank?
end

This code is saying that a password is required in two situations:

  • when the crypted_password is blank -- that situation happens when creating a new user, OR
  • when the class instance variable 'password' is not blank -- this can only happen when the variable has been accessed, such as when attempting to update a password.

The bug is in the test for !password.blank? because it's assuming that the user will enter something as a new password. To resolve that, I changed the code to this:
    def password_required?
crypted_password.blank? || !password.nil?
end

and now the validation is called (and fails) properly. More about this issue can be found in the last few posts on this page.

2 comments:

Unknown said...

Very helpful, thank you! Don't quite understand it fully yet though.

Ed Smiley said...

Yeah. I get it.

That line always bothered me. It didn't look right and I was meaning to go back and review that portion of the code.

I am making a lot of use of (forcing) the change password functionality in Acts As Authenticated, so that would certainly have bitten me.

Thanks.