Simple User Authentication in Rails with Devise — Part I

Before we get started, I’d like to explain the motivation behind this piece. When I was beginning development with Rails, adding even the most simple feature to my tiny apps was a daunting task. I imagine similar scenarios when working with other frameworks and projects and because of this, I’d like to walk through a feature that I implemented in a few of my projects that was a “small win”, and one that kept me motivated to expand my knowledge while building the respective apps. This tutorial is for someone that may be relatively new to rails or anyone that wants to add an awesome feature to their existing app.

Prerequisites:

  1. Get a good overview of Rails — Michael Hartl’s Rails Tutorial
  2. Maybe watch some of these — RailsCasts
  3. Build some simple Rails apps — Cloud9

RubyGems

I believe after going through some of the really good content listed above, you’ll be in a pretty good place to proceed with this guide. I’d like to stress that this guide will be a basic walk-through. Please visit The Devise Wiki for more in-depth material on the Devise gem. What is a gem? In short, a gem is a module/library that you can install and use in a respective project.

Above is a gem, (that I created) that contains a directory of all businesses that are registered in the city of San Francisco, California. If someone wanted to use biz_directory in their Rails project, they would simply have to include it in their gem file and run bundle install. This would give them the capability to use the library in their app! Learn more about RubyGems, here.

1. Create a new app:

Create a new Rails app and cd into it. I am working locally with Rails 5.0, OSX, terminal and Sublime as my text editor.

command: rails new deviseApp

rails new deviseApp

Our new app is created:

Open up your text editor. For sublime users, command: subl .

subl .

Lets clean up our terminal with the command: clear

clear

Above, we see the structure of our new app. Now is a good time to fire up rails server and test to see if our app is live, locally of course.

Open up a new terminal tab, and run the command: rails s

rails s

(this is short for rails server). If you run into any hiccups with starting up rails server, ensure that you are in the project directory of your app and try the command again. For even more help, check this thread out.

This is an underrated step. Feel good about getting this happy page to display, it’s one of the small humps that I had to get over when I initially started working with rails.

2. The Devise Gem.

Lets proceed to locate and open up our Gemfile, which should be located in the root directory of our app (see second to last picture above). Inside you’ll see a list of default gems that are included in our app. Go ahead and

add: gem ‘devise’ to the Gemfile, and save.

gem 'devise'

Back in the first terminal tab, run the command: bundle install which will install the devise gem in your app.

bundle install

Next, proceed to restart the rails server in the second terminal tab with the command: rails restart (or CTRL + C to stop server, and run rails s command again)

rails restart

3. Setup/Configure Devise

In the first terminal tab, lets setup Devise in our app by running the command: rails g devise:install (g is short for generate).

rails g devise:install

This will create two files for us:

Next, open up the development.rb file which will be in: app/config/environments/ path. We want to setup default URL options here.

Include the following line in the file:

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

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

Now save.

Finally, open up application.html.erb (app/view/layouts/) and include the following above the <%= yield %> line:

<% if notice %>
<p class=”alert alert-success”><%= notice %></p>
<% end %>
<% if alert %>
<p class=”alert alert-danger”><%= alert %></p>
<% end %>

Save.

4. Setup the Devise User Model for our user(s).

In the first terminal tab, run the following commands:

rails g devise user
rails db:migrate

The first command will generate our User model.

The second (non-complicated explanation) takes advantage of Migrations in rails to add (or prepare to add) respective data that we just generated, to our database in an organized manner. For more info on Migrations, see this page. You can check out the effects of running the migration by visiting your schema.rb file (app/db/).

It is worth mentioning that rails comes with support for SQLite. Rails defaults to using a SQLite database when creating a new project, but you can always change it later. If you’re using OSX 10.5 or above like me, you already have SQLlite. If not, you can install it via instructions here.

Okay, finally…restart your server.

rails restart

5. Creating a user/setting up views

With devise configured in our app, we’re finally in a position to get our first user created so that she/he can sign-in/sign-out of our app!

Keep in mind that if you were manually to implement an authentication feature such as this, you’d need views for a sign-in page, a sign-out page, new user registration page, etc.. Guess what? Devise takes care of the heavy lifting and gets the appropriate routes and views configured.

To see all the new routes in our app, run the command: rake routes in the first terminal window.

rake routes

Now go ahead and visit: http://localhost:3000/users/sign_up

Here, you’ll see a sign-up view that devise created for you! Yay! …okay, but what if you want to change the text, or add some color to your view in the future? Currently, you won’t be able to find any of the new devise views listed after you ran rake routes…lets fix this.

Run the command: rails g devise:views

rails g devise:views

You should now be able to see all the devise-generated views in app/views/devise/

Here’s the code for our sign-up page (devise/registrations/new.html.erb):

Now lets add some appropriate links to let the logged in user know, that they’re logged in! Go to: app/views/layouts/application.html.erb and below the <title> tag, add:

<p class="navbar-text pull-right">
<% if user_signed_in? %>
Logged in as <strong><%= current_user.email %></strong>.
<%= link_to 'Edit profile', edit_user_registration_path, :class => 'navbar-link' %> |
<%= link_to "Logout", destroy_user_session_path, method: :delete, :class => 'navbar-link' %>
<% else %>
<%= link_to "Sign up", new_user_registration_path, :class => 'navbar-link' %> |
<%= link_to "Login", new_user_session_path, :class => 'navbar-link' %>
<% end %>
</p>

Save.

Refresh the sign-up page. You should see some new links:

In Part II, we’ll discuss getting users created, actually authenticating them, and some awesome additional features that come packed with Devise!

Thank you for reading, and all feedback is welcome to make this guide better. Oh, and follow me on Twitter and Github!

Cheers,

Brinder Dhaliwal