In this tutorial, we will be dealing with Rails authentication with Devise.
If you don’t want to use Devise for authentication, you may refer to the article create basic authentication in Ruby on Rails instead.
Devise has been around for some time now and have been used and reviewed thousands of times and still receives security updates to date.
Not only that, it is also composed of other features such as reset password, email integration, and many more that can be a pain when creating your own authentication system.
Step 1: Initialize a Rails application
You can initalize a Rails application by running the following commands in the terminal.
rails new devise-app cd devise-app
Step 2: Install the Devise gem
Gemfile add the following:
And run the following in the terminal.
bundle install rails g devise:install
This will install and initialize the Devise gem in our Rails application.
Step 3: Create your model for authentication
In this example, we would be using
User as our model for authentication.
Run the following commands in the terminal.
rails g devise user rails db:migrate
This will create a migration file for our
User model then migrate it to complete.
Step 4: Add messages and navigation link to views
app/views/layouts/application.html.erb, add the following:
<% if user_signed_in? %> Logged in as <strong><%= current_user.email %></strong>. <%= link_to 'Edit Profile', edit_user_registration_path %> | <%= link_to 'Sign out', destroy_user_session_path, :method => :delete %> <% else %> <%= link_to 'Sign up', new_user_registration_path %> | <%= link_to 'Sign in', new_user_session_path %> <% end %> <%= notice if notice.present? %> <%= alert if alert.present? %>
This will show the current signed in user, a link to edit profile, a link to sign-out if there is a current user and will show a sign-up link and sign-in link instead otherwise.
alert are used to notify the user for the actions that have been made.
Step 5: Register a user
Now that we have a model, we can now register a new User. The Devise gem already created everything we need such as routes, models, etc. for our authentication to work.
Run your Rails server by running the following in the terminal.
Navigate to http://localhost:3000/users/sign_up in your browser and you should see a form.
Fill up the form and click Sign up.
It is up to you now to create your own views and to see all available routes generated by Devise you may run the following command in the terminal.
That’s it, we have now created a Rails authentication with Devise.