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
Let's try it out in the console.
user = User.create(
name: "Zack Siri",
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
#=> 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: "email@example.com").first
# then we call authenticate to see if it returns the user or false
We can now use this to create the user authentication controller.
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'