User authentication is an essential security feature for web applications, especially those that handle sensitive user data or provide restricted access to certain functionality. By requiring users to authenticate themselves before accessing the application, developers can ensure that only authorised users can view or modify the data and functionality of the application.

What is Devise?

Devise is a Ruby Gem that provides user authentication and authorisation features for Rails applications. It reduces the process of adding signup, login, and logout functionality to your application without having to write everything from scratch.

 It has built-in features such as password reset and account confirmation. It supports various authentication strategies such as email and password, OAuth, OpenID, and more.

Devise has detailed documentation that covers both basic and advanced features.

In this tutorial, we'll build a simple rails app with Devise that allows users to create accounts, sign in and sign out from their accounts. We'll also cover how to add style to the app using Bootstrap.

Prerequisites

Before starting this tutorial, you should have a good understanding of Ruby and Rails basics. Additionally, you must have the following software installed on your computer:

We will also cover how to use Bootstrap in Rails 7 later in the tutorial.

Step 1: Create a new Rails App

rails new authApp

This will generate a new Rails application called authApp in an authApp directory. Open this directory in your preferred text editor.

Step 2: Create a landing page

Step 3: Install and configure Bootstrap

<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> <%= javascript_importmap_tags %>

Step 4: Install and Configure Devise

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

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

Step 5: Creating User Model with Devise

<% if user_signed_in? %> 
  <p>Welcome, <%= current_user.email %>!</p> 
  <%= link_to "Sign out", destroy_user_session_path, method: :delete %>
<% else %>
  <%= link_to "Sign in", new_user_session_path %>
<% end %>

These lines create sign-up, sign-in, and sign-out links for your application. user_signed_in is a helper method provided by Devise that returns true if the current user is signed in and false if otherwise.

By following these steps, you have successfully integrated the Devise gem and set up user authentication for your application.

Conclusion

In this tutorial, we used Devise to add user authentication to our Rails app. We developed an application where users can create accounts, sign up and sign out. We also integrated Bootstrap to improve the project's appearance. To expand your knowledge of Devise and explore further helpers and methods, refer to the README file on the Devise GitHub repository.