Recently, I have written an overview of some popular authentication solutions for Rails. However, in many cases, having authentication by itself is not enough - you probably need an authorization mechanism to define access rules for various users. Is there an existing solution, preferably one that isn't very complex, but is still flexible?
Meet CanCanCan, a flexible authentication solution for Rails. This project started as CanCan authored by Ryan Bates, the creator of RailsCasts. However, a couple of years ago this project became inactive, so members of the community decided to create CanCanCan, a continuation of the initial solution.
In this article, I'll integrate CanCanCan into a simple demo project, defining access rules, looking at possible options, and discussing how CanCanCan can reduce code duplication. After reading this post, you will have a strong understanding of CanCanCan's basic features and be ready to utilize it in real projects.
The source code can be found on GitHub.
A working demo is available at sitepoint-cancan.herokuapp.com.
Preparing Playground
Planning and Laying the Foundation
To start hacking on CanCanCan we have to prepare a playground for our experiments first. I am going to call my app iCan because I can (hee!):
[ruby] $ rails new iCan -T [/ruby]I am going to stick with Rails 4.1 but CanCanCan is compatible with Rails 3, as well.
The demo application will present users with a list of projects, both ongoing and finished. Users with different roles will have different level of access:
- Guests won't have any access to the projects. They will only see the main page of the site.
- Users will be able to see only the ongoing projects. They won't be able to modify or delete anything.
- Moderators will have access to all projects with the ability to edit the ongoing ones.
- Admins will have full access.
Our task will be to introduce those roles and define proper access rules for them.
Continue reading %CanCanCan: The Rails Authorization Dance%
by Ilya Bodrov-Krukowski via SitePoint
No comments:
Post a Comment