Ruby On Rails Classroom image

Neha  Jaggi / Professional / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  ||
Lessons:- An Encrypted Password

  An Encrypted Password

We’ll start with the necessary change to the data model for users, which involves adding a password_digest column to the users table (Figure 6.5). The name digest comes from the terminology of cryptographic hash functions, and the exact name password_digest is necessary for the implementation in Section 6.3.4 to work. By encrypting the password properly, we’ll ensure that an attacker won’t be able to sign in to the site even if he manages to obtain a copy of the database.

We’ll use the state-of-the-art hash function called bcrypt to irreversibly encrypt the password to form the password hash. To use bcrypt in the sample application, we need to add the bcrypt-ruby gem to our Gemfile (Listing 6.24).



Then run bundle install:

bundle  install



Since we want users to have a password digest column, a user object should respond to password_digest, which suggests the test shown in Listing 6.25.


To get thetest to pass, we first generate an appropriate migration for the password_ digest column:

$ rails generate migration add password digest to users password digest:string


Here the first argument is the migration name, and we’ve also supplied a second argument with the name and type of attribute we want to create. (Compare this to the original generation of the users table in Listing 6.1.) We can choose any migration name we want, but it’s convenient to end the name with _to_users, since in this case Rails automatically constructs a migration to add columns to the users table. Moreover, by including the second argument, we’ve given Rails enough information to construct the entire migration for us, as seen in Listing 6.26.  



This code uses the add_column method to add a password_digest column to the users table. We can get the failing test from Listing 6.25 to pass by migrating the development database and preparing the test database:


bundle  exec  rake  db:migrate
bundle  exec  rake  db:test:prepare
$  bundle  exec  rspec  spec/


Neha  Jaggi

Skills    Ruby On Rails

Qualifications :- High School - , College/University - Graphic Era Hill University, Dehradun, College/University - ,
Location :-Dehradun,Dehradun,UTTARAKHAND,India

Experienced Software Developer with a demonstrated history of working in the Information Technology and services industry. Skilled in Web Technologies (Ruby on Rails, PostgreSQL, php, Laravel and AJAX). 


  Students (0)