Securing user the password

Every information sent on the web is sent in plain, therefore during signup user sentive details like password are also sent in manner making it easy for sniffers to intercept.

Inorder to secure the password we need to hash it.Hashing is usage algorithmm to encrypt data. There are different hashing libraries/ gems out there but in our case we will use bcrypt

Setting up bycript

1
$ git checkout -b secure-password orgin/master

On add this outside the blocks.

1
 gem 'bcrypt'

Run bundle

1
$ bundle

creating password digest

Let start with test

On the spec/model/user_spec.rb on #validation of user attributes block add this test

spec/model/user_spec.rb

1
 it {is_expected.to have_secure_password }

When you run your test it fails indicating no authentication, password digest and passwordigest=

To achieve we use has_secure_password method.

app/model/user.rb

1
2
# trunctated for brevity
has_secure_password

Run test again this time password digest is not availabe. has_secure_password creates virtual columns password and password_confirmation on the database and requires field password_digest to be on the database.Password digest is hashed version of password.

The problem we are facing require us to two things:

  1. delete password column from the users table

  2. add password digest column on the users table

To achieve this we need to create a migration.Migration help us update our database to the state we want its table to be.In this case we are updating users table.For on migration visit migrations

Let us create our migration like so:

1
2
$ rails generate migration add_password_digest_to_users
password_digest:string

Edit db/migrate/[timestamp]_add_password_digest_to_users.rb file like so:

1
2
3
4
  def change
    add_column :users, :password_digest, :string
    remove_column :users, :password
  end

Run the migration.

1
$ rails db:migrate

Since logic has change our test also has to change

Let us remove the test expected availability of password column since we removed it and replace it with a test expecting availability of password_digest column

Run the test again.It passes

Let us push our work.

1
2
3
$ git add .
$ git commit -m "secure password"
$ git commit push origin secure-password