开发者

Dynamic Role Authorization in Rails using a database. Declarative Authorization the best choice?

I will need to provide dynamic role assignments (Roles/ Privileges) .More clearly, an end user should be able to create a role, assign permissions to a new user. So I was thinking of storing roles and privileges in a table for each user.

Is there a smart way to do this (any oth开发者_JAVA技巧er plugin?),or or should I write code to do this with Declarative Authorization . Some light would help.Thanks!


Try answering these to get closer to a solution:

  1. Are the roles themselves dynamic? i.e. Can the privileges assigned various to roles can be changed through the web interface by an Admin? If yes, then you should be storing this information into your database. For a system like a blog, where roles are pre-defined eg. Admin, Guest and Moderator, Declarative Authorization works like a charm.
  2. How strong is the coupling of permissions to the UI? (Sometimes it just a couple of places you need to restrict, in other cases, like a social network, permissions are a lot more complex and coupled tightly with the UI). If its very tightly coupled, i.e. one action is available to all sorts of roles but the actions these roles perform are limited by their definition, then Declarative Authorization (or the likes) won't help much, you need a legacy system.


I've used CanCan recently in a project and think it was pretty cool. You create an Ability class and use it to decide if the user 'can' perform the action... You could check for existence of permissions in a table in the method, or if their ruleset permits the action.

I took all of this sample code from the github readme:

class Ability
  include CanCan::Ability

  def initialize(user)
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end

Then in your views and your controller you can check authorization levels

<% if can? :update, @article %>
  <%= link_to "Edit", edit_article_path(@article) %>
<% end %>


def show
  @article = Article.find(params[:id])
  authorize! :read, @article
end


Cancan is great for simple/starting projects but you should definitely wrap it if you have a monolithic app. Cancan should be a early solution but not a final one. If your looking at policy objects (pundit) it might be a code smell you need to build your own authorization model. Authorization like integration varies client to client and if your looking for more dynamic solutions or you have too many roles to speak of, cancan is not for you. You may need a more data-driven security model. For example if you can grant someone else access to an entity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜