BCrypt and Rails
If you are creating your first rails app and you need to add user authentication functionalities to it, don't worry I got the perfect gem for this called BCrypt used to add a layer of protection to your app users’ information.
But Gary, Why should I use a BCrypt algorithm? Well if you save the information of your users as it comes,if hackers make their way into the database and retrieve its information. They might obtain useful information like emails, usernames and passwords combination that you users use in in other webpages and systems. BCrypt is a gem for hashing information, that way if the information is leak from the database it won’t be readable through normal means.
Regular hashing algorithm have a weakness, attackers can just run lists of possible passwords through the same algorithm to get the actual password back. What makes BCrypt different than other hashing algorithm is the salt. A salt is a random string that makes the hash unpredictable. Bcrypt is a popular and trusted method for salt and hashing passwords.
Adding a salt indicates that the hacker must have a collection of unique salts to match it with the hashing algorithm and if the salt is 4 characters long, it means 456,976 possible salts.
Using BCrypt, ActiveRecord and Rails
In this example we are going to be using BCrypt 3.1.7 and we will be implementing a secured password for an User Class. The first step would be installing the BCrypt Gem to your rails app. The Gem is already commented in your gem file, just remove the comments and run bundle install.
Now that BCrypt is available for our app, we need to add add our User model migration to our project.
rails g migration user name:string email:string password_digest:string
Then in our model we just include has_secure_password .
The password_digest attribute allows rails to know that we want to hash that attribute. It works together with a virtual password attribute that is added to manage user passwords.
Creating an user
To create an user is as simple as passing the need paramaters.
Authenticating an user
To authenticate we only have to look for the user by its email and invoke the authenticate method if any user has been found. Authenticate will take the password and return true if it match and false if it does’nt.