Now that we’ve defined validations for the name and email fields, we’re ready to add the last of the basic User attributes: a secure password. The method is to require each user to have a password (with a password confirmation), and then store a hashed version of the password in the database.
A hashed password
The secure password machinery will be implemented using a beforeCreate, beforeUpdate method and bcrypt module
To implement the data model, we first generate an appropriate migration for the password_digest column.
We use the addColumn method to add a password_digest column to the user table.
To apply it, we just migrate the database
To make the password digest, we use a state-of-the-art hash function called bcrypt
User has secure password
The tests are now failing, as you can confirm at the command line
To get the test suite passing again, we just need to add a password and its confirmation
Now the tests should be successful
Minimum password standards
It’s good practice in general to enforce some minimum standards on passwords to make them harder to guess. Picking a length of 6 as a reasonable minimum leads to the validation test
You may be able to guess the code for enforcing a minimum length constraint by referring to the corresponding maximum validation for the user’s name
At this point, the tests should be successful
Creating and authenticating a user
Now that the basic User model is complete, we’ll create a user in the database as preparation for making a page to show the user’s information in “Showing users” Section.
The authenticate method in model determines if a given password is valid for a particular user by computing its digest and comparing the result to password_digest in the database. In the case of the user we just created, we can try a couple of invalid passwords as follows:
Here user.authenticate returns false for invalid password. If we instead authenticate with the correct password, authenticate returns the user itself