How to configure/set up Devise authentication for Ruby on Rails

Devise is a Ruby gem that provides a flexible authentication solution for Rails applications. It includes everything we need to authenticate our users, including:

  • User registration and login

  • Password reset and confirmation

  • Remember me functionality

  • Locking users out after too many failed login attempts

  • Support for multiple authentication mechanisms, such as email and social login

Devise is easy to configure and use. We can perform the following steps to configure and set up Devise authentication for Ruby on Rails:

  1. Firstly, we add the appropriate gem to the Gemfile as follows:

gem 'devise'
  1. After adding the gem to the Gemfile, we save the file. Following this, we execute the subsequent command in the terminal to perform the installation:

bundle install
  1. Once Devise is installed, we create the Devise model as follows—this command will create an initializer file and display instructions for further setup:

rails generate devise:install

  1. We open the config/environments/development.rb file and incorporate the subsequent line. We can replace localhost and 3000 with our desired host and port.

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

  1. We run the following command to add a Devise model (e.g., User):

rails generate devise User
  1. We execute the following command to implement the Devise-related database migrations:

rails db:migrate
  1. We open the app/views/layouts/application.html.erb file and insert the following lines within the <body> tag. These lines will display flash messages for authentication-related notifications.

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

  1. This is an optional step. To customize the parameters that Devise can accept during user registration, we access the app/controllers/application_controller.rb file and insert the following method. Moreover, we replace :username and :email with the desired additional parameters.

before_action :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :email])
end
Method to customize parameters

  1. Within any controller or the routes.rb file, we include the following line to safeguard the routes necessitating authentication. We replace :authenticate_user! with the appropriate method for our Devise model.

before_action :authenticate_user!

  1. We execute the following command to initiate our Rails server:

rails server

Your application should now be set up with Devise authentication. You can visit http://localhost:3000 (or your configured URL) in your browser to see the application running.

These steps provide a basic configuration of Devise authentication in a Ruby on Rails application. Please refer to its documentation for further learning.

Example app

Here is an example application of Ruby on Rails with Devise authentication.

Note: Start the application by clicking the “Run” button. Click the link below to open the app in the browser.

#!/usr/bin/env ruby
# frozen_string_literal: true

#
# This file was generated by Bundler.
#
# The application 'bundle' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "rubygems"

m = Module.new do
  module_function

  def invoked_as_script?
    File.expand_path($0) == File.expand_path(__FILE__)
  end

  def env_var_version
    ENV["BUNDLER_VERSION"]
  end

  def cli_arg_version
    return unless invoked_as_script? # don't want to hijack other binstubs
    return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
    bundler_version = nil
    update_index = nil
    ARGV.each_with_index do |a, i|
      if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
        bundler_version = a
      end
      next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
      bundler_version = $1
      update_index = i
    end
    bundler_version
  end

  def gemfile
    gemfile = ENV["BUNDLE_GEMFILE"]
    return gemfile if gemfile && !gemfile.empty?

    File.expand_path("../Gemfile", __dir__)
  end

  def lockfile
    lockfile =
      case File.basename(gemfile)
      when "gems.rb" then gemfile.sub(/\.rb$/, ".locked")
      else "#{gemfile}.lock"
      end
    File.expand_path(lockfile)
  end

  def lockfile_version
    return unless File.file?(lockfile)
    lockfile_contents = File.read(lockfile)
    return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
    Regexp.last_match(1)
  end

  def bundler_requirement
    @bundler_requirement ||=
      env_var_version ||
      cli_arg_version ||
      bundler_requirement_for(lockfile_version)
  end

  def bundler_requirement_for(version)
    return "#{Gem::Requirement.default}.a" unless version

    bundler_gem_version = Gem::Version.new(version)

    bundler_gem_version.approximate_recommendation
  end

  def load_bundler!
    ENV["BUNDLE_GEMFILE"] ||= gemfile

    activate_bundler
  end

  def activate_bundler
    gem_error = activation_error_handling do
      gem "bundler", bundler_requirement
    end
    return if gem_error.nil?
    require_error = activation_error_handling do
      require "bundler/version"
    end
    return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION))
    warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`"
    exit 42
  end

  def activation_error_handling
    yield
    nil
  rescue StandardError, LoadError => e
    e
  end
end

m.load_bundler!

if m.invoked_as_script?
  load Gem.bin_path("bundler", "bundle")
end
Demo Rails application with Devise authentication

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved