CSC/ECE 517 Spring 2016/Refactor review mapping controller.rb

From Expertiza_Wiki
Revision as of 04:47, 7 February 2016 by Skunapa (talk | contribs)
Jump to navigation Jump to search

Template:Infobox software Devise is a rack based full-fledged authentication system for Rails. It is a complete MVC solution meaning it can support various models, views and controllers as part of its code and can be used be directly by developers. Devise is simple to use and starts up with a couple of commands but it is also highly customizable. Devise saves a lot of time and effort as many applications require user registration and authentication mechanisms which are difficult to develop from scratch.

History

Devise is first introduced in January 2010 by Plataformatec, a company which builds web and mobile applications. Devise is one of the few authentication systems which support rack based applications and hence can support Rails 3 and up as they are completely rack based. The latest version of Devise available is v3.5.3 and it is up to date with Rails 5 beta 2.

Warden

Devise gem is built on top of a rack application called Warden which is used to verify the identity of logged in user using a session string. In Warden, the id which is a primary key of a user is somehow stored to match it later with the logged in user. Warden also provides restricted access to guest users depending on the functional requirements of an application.

Since Warden does not know of the existence of the Rails application, it cannot provide any helper methods, controller classes, views etc. This is where Devise comes into play and can integrate with Rails seemlessly. Devise interacts often with Warden using Strategy design pattern for encrypting passwords, HTTP Authentication etc.

Installation

Although Devise is very useful and reduces the amount of effort in developing authentication mechanisms significantly, it requires a good understanding of the Rails framework. Hence it is advised for beginners to not use Devise.

There are several commands that are required for the successful installation of Devise. They are listed out below:

  • Add the devise gem to your gemfile.
gem 'devise'
  • Run bundle command to install the gem.
bundle install
  • You need to run the generator next which will install an initializer and creates all the configuration files.
rails generate devise:install
  • Now you can add Devise to any of your models using the generator. This will create a class with the model name given and routes etc. The model will be configured with default Devise modules. The config/routes.rb file will be configured to point to the Devise controller.
rails generate devise user //Assuming that the model name is user
  • Next, add any configuration changes that are required and then run:
rake db:migrate
  • The following step will create Devise views but is optional. Devise has views for every generic operation like Login or SignUp and can be used directly instead of creating custom views.
rails generate devise:views users
  • There are also many routes that are defined in config/routes.rb with a line like:
devise_for :users

Modules

When a devise generator is invoked a model class is created in app/models for you modify for your specific application requirements. This is the place where many important configuration changes are specified. Perhaps the most important are the Devise modules which provides essential functionalities like enhanced securtiy.

There are 10 modules listed on the official page of Devise by Plataformatec. These modules are features that are contained in Devise and can be used by the developers depending on the use-cases or requirements of their application. Below is the list of modules:

  • Database Authenticable
  • Omniauthable
  • Confirmable
  • Recoverable
  • Registerable
  • Rememberable
  • Trackable
  • Timeoutable
  • Validatable
  • Lockable

Information regarding each module is listed in README as well as the Plataformatec website. The modules are included in an application in this way:

class User < ActiveRecord::Base
  devise :database_authenticable, :omniauthable, :confirmable, :rememberable,
          :trackable, :timeoutable, :lockable
end

In addition to the classes generated Devise also generates a database migration in which fields related to the functionalities of these modules are added. Each field is related to a specific module and hence when a module is not require some of the fields may be removed from the migration to the database. Also most of these modules have specific forms and view associated with them. The forms are used by an end user to type in his/her information which will then be sent to the Devise controllers.

Methods

There are many classes in Devise which include models, controllers, helpers, views, routes etc. But much of the functionality offered by Devise is exposed via simple helper methods. Some of the most important methods which can be used in building our own application are:

  • authenticate_user! : This method is used to check whether a user is logged in before he/she attempts to perform a specific set of controller actions. authenticate_user! may be called with before_action as shown below to ensure the user is logged in before performing any of the operations.
before_action :authenticate_user!

If only some of the actions need authentication and some do not, we can use except clause so that only some actions are blocked as guest and others are accessible. The code with except clause is as below:

before_action :authenticate_user! except [:index, :show]

In the above example index and show are two controller actions associated with operations which do not require user authentication and can be browsed as a guest.Authenticate user may also be used with in a controller action so that it is application only for that specification. We need to use before_filter instead of before_action to achieve this purpose.

class EndUserBaseController < ApplicationController
   before_filter :authentication_user!
end

In this example the application will authenticate a user only if he is trying to perform an action associated with the EndUserBaseController. If in any of the above cases a user is not logged in the application backs off and redirects to its sign-in page.

  • current_user : current_user method is used to return the model class corresponding to the user who is currently signed in. For example, if you are building a messaging application, you may retrieve all the sent messages of a user as:
class SentMessagesController < ApplicationController
   before_filter :authentication_user!
   def index
     @sent_messages = current_user.sent_messages.all
   end
end

Notice how authenticate_user! is used before checking the messages of the current user so as to ensure that the user is signed in before checking his/her messages.

  • user_signed_in? : As the name suggests, user_signed_in? method is used to check whether a user is signed in. This is useful when you want to show two different pages depending on whether a user has logged in or not. For example, when a user is logged in you want to show him/her an option to Logout otherwise you want to show Register or Login options.
<% if user_signed_in? %>
  <li><%- link_to "Logout", destroy_user_session_path, method :delete %></li>
<% else %>
  <li><%- link_to "Sign Up", new_user_registration_path %></li>
  <li><%- link_to "Login", new_user_session_path %></li>
<% end %>

We need to use method :delete to logout so that Devise will only logout when a HTTP delete request is made by user and does not accidentally logout because of a malicious link that automatically logs out the user.

  • sign_in(@user) and sign_out(@user) : These methods are used to login(sign_in(@user)) or logout(sign_out(@user)) a newly created or existing user.
  • user_session : This method returns metadata about the user that is currently logged in.

The methods that are most frequently used by developers are current_user and user_signed_in? which are present as helper methods. Also if the methods are to be referred to an Admin then replace user in each method with admin i.e. current_user becomes current_admin etc.

See Also

References