Sunday, January 29, 2017

Role-based Authorisation in Rails

Simply add access-granted to your Gemfile:
gem 'access-granted', '~> 1.0.0'
then bundle and run the generator to create your starter AccessPolicy:
rails generate access_granted:policy
which you can find in app/policies/access_policy.rb.
Forums are a good showcase of user hierarchy I mentioned above, because they usually need a hierarchical permission system based on the following roles:
  • moderators
  • registered users
  • guests
The order in which roles are sorted is also the order of importance. The moderator is the role with the most permissions and the guest is the role with the least.
In Access Granted roles are defined in the same, top-to-bottom, order:
class AccessPolicy
  include AccessGranted::Policy

  def configure
    role :moderator, proc { |user| user.moderator? } do
      # permissions will go here
    end

    role :member, proc { |user| user.registered? } do
      # permissions will go here
    end

    role :guest do
      # permissions will go here
    end
  end
end
Every role has a name and an optional predicate to check if it’s active for the user.
Note: Above you can see me using .moderator? and .registered? methods inside the Procs - these are app-specific and may come from, for example, ActiveRecord::Enum module.

More at
https://blog.chaps.io/2015/11/13/role-based-authorization-in-rails.html

No comments:

Welcome to Rails.. Rails... Rails !

In 1995, I started the popular Clipper...Clipper... Clipper website (no blogs then) which was very popular and linked by virtually every Clipper-related site. When I switched to Windows via Delphi in 1997, I started the Delphi... Delphi... Delphi site. In June 2007, I discovered Ruby on Rails and no prize for guessing what I am gonna name this blog. which I started on 2nd October 2007.

As at 10th June 2010, we have 13,364 unique visitors from more than 84 countries such as Angola, Andorra, Argentina, Australia, Austria, Algeria,Barbados, Bosnia and Herzogovina, Belgium, Brazil, Bulgaria, Bangladesh, Belarus, Bolivia, Chile, Cambodia, Cape Vede, Canada, China, Colombia, Costa Rica, Croatia, Cyprus, Czech Republic, Denmark, Egypt, Estonia, Finland, France, Guadeloupe, Guatemala, Germany, Greece, Hong Kong, Hungary, India, Indonesia, Ireland, Israel, Italy, Japan, Kenya, Korea, Lithuania, Latvia, Malaysia, Mexico, Macao, Netherlands, Nepal, Norway, New Zealand, Oman, Panama, Peru, Poland, Portugal,Paraguay , Philippines, Romania, Russian Federation, Saudi Arabia, Singapore, Spain, Slovakia, Slovenia, Serbia, South Korea, Slovenia, South Africa, Spain, Switzerland, Sri Lanka, Sweden, Taiwan, Thailand, Turkey, United Arab Emirates, Ukraine, USA, UK, Venezuela, Vietnam

CCH
10th June 2010, 19:42