You create an online web application and you want to define its access policy for the resources which you wish to protect? Or maybe you want to verify the identity of users visiting your website? In this tutorial, I will show you how simple it is to authenticate and authorizate your application using the popular rails gems: Devise, CanCanCan, and Rolify.
What is authentication and authorization?
Authentication is a confirmation of user identity, while authorization determines whether you can access a particular resource.
What is Devise?
Devise is a flexible authentication solution for Rails. It is composed of 10 modules. For example, one module called Trackable, tracks sign in counts, timestamps, and locates IP addresses. Creating a user authentication system is piece of cake when using Devise.
What is Rolify and CanCanCan?
Rolify is Roles library which supporting scope on resource object without any authorization enforcement. CanCanCan is an authorization library which restricts what resources a given user is allowed to access. All permissions are defined in a single location (the Ability class).
Step 1. Create a new Rails application
I used 4.2.6 version of Rails and SQLite as a database. Let’s skip a test and create a new Rails application.
$ rails new shop --skip-test-unit
$ cd shop
$ rake db:create
Step 2. Add Bootstrap and styles
Let’s add a ‘bootstrap-sass’ gem to our Gemfile. After cleanups and adding this gem, your Gemfile should look like this:
gem 'rails', '4.2.6'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'bootstrap-sass', '~> 3.3.6'
group :development, :test do
group :development do
gem 'web-console', '~> 2.0'
Then bundle everything:
$ bundle install
Now let’s add some styles to our application. First, rename the application.css to the application.scss under the app/assets/stylesheets – in order to use imports. Now add these lines after the manifest:
//= require bootstrap-sprockets