Rails authentication using has_secure_password

If you have been following recent blog posts you would've seen that this site was migrated from Drupal to Sinatra. Well now it's been migrated from Sinatra to Ruby on Rails, all just for fun. On doing this migration a very simple authentication system was needed to allow some users to add new blog posts.

The first step is to uncomment gem 'bcrypt-ruby', '~> 3.0.0' in the Gemfile as this is needed by rails to encrypt the password. A migration can then be added to create the users table with an email and password_digest column

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :password_digest

      t.timestamps
    end
  end
end

This then needs a User model, you can see here that in the model has_secure_password is being set.

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation
  has_secure_password
  validates_presence_of :password, :on => :create
end

A standard controller can then be created with routes to display a form with email and password fields. This can then submit to an action such as:

def create
  user = User.find_by_email(params[:email])
  if user && user.authenticate(params[:password])
    session[:user_id] = user.id
    redirect_to admin_root_path, :notice => "Welcome back, #{user.email}"
  else
    flash.now.alert = "Invalid email or password"
    render "new"
  end
end

You will see this create action first checks for the user in the database using the email address submitted, using the authenticate method it checks if the user exists and if their submitted password matches the one in the database. Upon successful authentication is sets the user id into a session and in this case redirects to the admin page with a welcome message. If authentication fails, or the user simply doesn't exist, an alert will be displayed and the login form (in this case in the new action) is displayed.

That's all there is to it, has_secure_password along with the authentication method takes away all the pain and fuss of password encryption and validation.

Looking for some help adding authentication to your Ruby on Rails app? get in touch

Simple SEO PDF guide

Get our latest PDF guide, Simple SEO.

Twitter