Securing rails activerecord with password cannot be any easier.
Lets say we have a user table that contains password and we would like to secure this from external access.
I assume you already have a controller. So lets go ahead and create our model.
1. Run the following command
rails g model User name email password_digest password_confirmation reputation
2. Run its serializer.
rails g serializer User name email password_digest password_confirmation reputation
3. Next, lets modify our User ActiveRecord by adding a new field called 'has_secure_password', as shown in diagram below :-
This is basically part of bcrypt (a.k.a blowfish encryption) implementation.
Here are the specification
a) In our database, we need a field called 'password_digest'
b) In our ActiveRecord, we need to specify 'has_secure_password'
4. Next, we just need to run rake.
This ensure we have created the necessary table structure for our database.
5. We need to wire this up in our controller. Lets say we have a controller called Home and our code might look like something below :-
6. Let's go and see our model in action using rails console. From the command line, type rails console. We will create a new user by using the following command
u = User.new()
u.name = 'jeremy'
u.email = 'email@example.com'
u.password = 'test'
If you look at the output, you will see our field 'password_digest' is automatically populated with hashed characters. From here, i wanted to highlight that the proper way to authenticate is via u.authenticate('abc') => false. If we try u.authenticate('test') => true !success.
Now, lets make a get request to our home controller. From the browser link, type http://localhost:3000/home/index. It will returns the following json response to you. Notice that password is null.