Skip to Content
Course content

127: Devise for Authentication

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I once worked with a junior developer who spent nearly a week building a custom authentication system from scratch. He had the basic login and logout working, but then he hit the "Forgot Password" requirement. He spent another three days wrestling with secure token generation, expiration timestamps, and mailer logic. By the time he showed me the code, he was exhausted, and the implementation had a glaring security hole because he was storing the reset tokens in plain text. I told him to stop everything and install Devise. It's a rite of passage for Rails developers to try and "roll their own" auth once, only to realize that security is a massive rabbit hole you don't want to fall down alone.

Devise is essentially the industry standard for authentication in Ruby on Rails. Instead of you writing the logic for hashing passwords, managing sessions, and handling account confirmations, Devise provides a flexible "engine" that plugs into your app. It handles the heavy lifting of security best practices so you can actually spend your time building the features your users care about.

Installing the Engine

To get started, you'll add the gem to your Gemfile and run the generator. But before you run the migrations, you need to handle the environment setup. Devise requires a few things to be in place, like a root route in your config/routes.rb and a way to send emails (even if it's just the default development logger).

# Add to Gemfile
gem 'devise'

# Then run in your terminal
bundle install
rails generate devise:install

After running the install generator, you'll see a bunch of instructions in your terminal. Don't ignore them. You'll need to configure your config/environments/development.rb to define the default URL options for your mailers. If you don't, your app will crash the second Devise tries to send a password reset email.

Configuring the User Model

Once the engine is installed, you need a model to hold your user data. Devise provides a generator that creates the model and the necessary migration with all the columns you'd normally have to guess at (like encrypted_password and reset_password_token).

rails generate devise User
rails db:migrate

If you look at your user.rb model now, you'll see a line that says devise :database_authenticatable, :registerable, .... These are modules. You can pick and choose which ones you want. For example, if you want to manually approve users instead of letting anyone sign up, you'd remove :registerable. If you don't need password recovery, drop :recoverable. Most of the time, the defaults are exactly what you need, but knowing you can toggle these features is where the real power of Devise lies.

Locking Down the App

Having a User model is great, but your pages are still public. To actually protect a part of your application, you use a helper method provided by Devise called authenticate_user!. I usually wrap this in a before_action at the top of the controller.

class ProjectsController < ApplicationController
  before_action :authenticate_user!

  def index
    @projects = current_user.projects
  end
end

The moment a visitor hits that index action, Devise checks if a session exists. If not, it redirects them to the login page with a friendly flash message. Once they are logged in, Devise gives you the current_user helper, which is a lifesaver for scoping data. Instead of searching for users by an ID in the session, you just call current_user to get the actual User object for the person currently browsing.




📋 Practical Task

Securing the Secret Recipe Vault

You are building a "Secret Recipe Vault" application. Currently, any guest can see the recipes, which defeats the purpose of the vault. Your goal is to implement Devise and restrict access to the recipes.

  • Add the devise gem to your project and run the installation generator.
  • Configure your development mailer settings in config/environments/development.rb.
  • Generate a User model using the Devise generator and run the migrations.
  • Create a RecipesController with an index action that lists all recipes.
  • Implement a before_action in the RecipesController to ensure that only authenticated users can view the list of recipes.
  • Verify that attempting to visit /recipes without logging in redirects you to the sign-in page.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.