Rails foundationSort Order

Rails: User Authentication Concepts

In this episode we walk you through some of the concepts behind user authentication. We start by generating the user model and talk about the different attributes involved. We then show you the concepts behind password confirmation and not storing plain text password in your database.

Let's begin by generating our User Model

rails g model user name:string email:string password_digest:string

We will also be using the has_secure_password method in Rails which depends on the bcrypt gem so let's uncomment it from our Gemfile

gem 'bcrypt', '~> 3.1.7'

In our User model let's add the has_secure_password macro

class User < ActiveRecord::Base  has_secure_passwordend

Authenticating Users

Let's try it out in the console.

user = User.create(  name: "Zack Siri",   email: "zack@codemy.net",   password: "12345678",   password_confirmation: "12345678")

This will create the user and you will see that the password_digest field is automatically hashed for us by the has_secure_password macro. We can also try the authentication method

user.authenticate("abcdefgh") #=> falseuser.authenticate("12345678")#=> returns user

So normally the flow of the authentication process would be that we load the user using the email, like so.

user = User.where(email: "zack@codemy.net").first# then we call authenticate to see if it returns the user or falseuser.authenticate("12345678")

We can now use this to create the user authentication controller.

Password Validation

The has_secure_password macro also validates the password for us when we want to change the password. It ensures that the password field and password_confirmation matches before modifying the password. Let's try changing our password

user.password = 'abcdefgh'user.password_confirmation = 'abcdefgh'user.save