[Ruby On Rails] Authentication – Devise Gem

You can use the built-in “has_secure_password” feature for authentication. But there are many 3rd party gems that you can use very easily. I will talk about the one of the popular gems : “Devise”

1. Install Devise

In the “GemFile“,

gem 'devise'

And then run the following commands.

> bundle install
> rails generate devise:install    # config/initializers/devise.rb
> rails g devise User
> rake db:migrate

 

2. Config Routes

In the “config/routes.rb“, add the following routes:

devise_for :users

Devise provides many routes. Please check the available links.

> rake routes

 

3. Views and Controllers

Controllers and default views are alredy embedded in the gem.

 

4. Helpers

Devise” provides the following helpers

  • authenticate_user! 
  • user_signed_in? 
  • current_user 
  • user_session

 

5. Securing Controller Actions

You can secure actions in the controller.

before_action :authenticate_user!, except: :index

 

6. Sign-up Link

The sign-up view is already in the gem.

<p>
  <%= link_to "Sign Up", new_user_registration_path, class: "btn btn-primary" %>
</p>

 

7. Login and Logout Links

Views are already in the gem. You can style the views using CSS.

<% if user_signed_in? %>
  <li><%= link_to current_user.email, edit_user_registration_path %></li>
  <li><%= link_to "Sign Out", destroy_user_session_path, method: :delete %></li>
<% else %>
  <li><%= link_to "Sign In", new_user_session_path %></li>
<% end %>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s