paint-brush
How to Add User Authentication using Devise (Bootstrap in Rails 7)by@Temmarie
2,670 reads
2,670 reads

How to Add User Authentication using Devise (Bootstrap in Rails 7)

by Grace Tamara EkunolaJune 28th, 2023
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Devise is a Ruby Gem that provides user authentication and authorisation features for Ruby applications. 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.
featured image - How to Add User Authentication using Devise (Bootstrap in Rails 7)
Grace Tamara Ekunola HackerNoon profile picture

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:


  • Ruby: If you haven't installed Ruby on your machine, you can download the latest version from the official Ruby website.
  • Ruby on Rails: You should set up your local development environment by following the Rails guide.
  • Node.js: Install Node.js to manage the asset pipeline and run JavaScript code.
  • Yarn
  • SQLite3
  • A text editor like Visual Studio Code
  • A browser like Google Chrome


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



Step 1: Create a new Rails App

  • To create a new rails app, open a terminal in your preferred directory and run the command:
rails new authApp

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

  • Navigate to the app directory by typing: cd authApp
  • In your terminal, start your Rails server by running: rails server
  • Open http://127.0.0.1:3000/ in your browser to access the Rails welcome page.

Rails Welcome Page



Step 2: Create a landing page

  • Generate a new controller that will handle the request to the root path using the command: $rails generate controller home index

    This creates a new controller named `Home` with an action `index`.

  • Add the root path to the routes.rb file in the ‘config’ folder by adding the following line: root 'home#index'

  • In the app/views/home directory, you will find a new file called index.html.erb. This view will contain the HTML code for your landing page.

  • Restart the server and check the local host in your web browser to view your newly created landing page.


Home Page


Step 3: Install and configure Bootstrap


  • In this section, we'll be using import maps, which load JS. First, check if you have import maps installed by running cat config/importmap.rb. If you don't, run rails importmap:install
  • Next, add Bootstrap 5 JS to Rails via import maps: $ bin/importmap pin bootstrap. This adds JS, bootstrap and popperjs to config/importmap.rb.
  • Import Bootstrap in app/javascript/application.js using import 'bootstrap';.
  • Add gem 'bootstrap', '~> 5.1.3' to your Gemfile and run bundle install.
  • In app/assets/stylesheets/application.css, import Bootstrap using @import "bootstrap"; and rename the file to application.scss.
  • Make sure your app/views/layouts/application.html.erb file contains:
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> <%= javascript_importmap_tags %>
  • Add styles as preferred in your app/views/home/index.html.rb file.
  • Reload the server and see the changes.


Home page with Bootstrap styles


Step 4: Install and Configure Devise

  • Navigate to the Gemfile and add the Devise gem using the command:

    gem 'devise', github: 'heartcombo/devise', branch: 'main'

  • Run bundle install to install Devise.

  • Run rails g devise:install to set up Devise in your project. This generates several starter files for Devise and provides instructions in the terminal.

  • Uncomment the line config.navigational_formats = ['*/*', :html, :turbo_stream] in the devise.rb file. This adds turbo_stream as a navigational format, which is required for Devise 4.9.2 to work with Rails 7. Failing to do this will result in an undefined method user_url error.

  • Open app/layouts/applications.html.erb and add the following lines for notice and alert messages:


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

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



Step 5: Creating User Model with Devise


  • To create a user model with Devise, run rails g devise user in the terminal. This will generate the necessary files and configuration needed for implementing user authentication.

  • Create the user table by running the migration command: rails db:migrate.

  • Restart the server to load the new Devise initializer file and set up everything for user authentication to work.

  • Go to http://localhost:3000/users/sign_up in your browser to access the sign-up form to create an account by entering an email and password.


  • Navigate to the index.html.erb file and add the following lines of code:

<% 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.


  • Refresh your page in the browser to review the changes.



Signed In Page



  • To review the changes, simply refresh the page in your browser. If you haven't already signed in, there will be a sign-in button visible on the screen. Click on it and complete the registration process. Once you have successfully signed up, you will be directed to the landing page where you can view the email address of the currently signed-in user, a welcome message, and a sign-out button.


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.