cancan 使用介绍
####在Gemfile添加
gem "cancan"
####生成相应model:
rails g cancan:ability
####权限配置 #####ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.role?(:admin)
can :manage, :all
elsif user.role?(:author)
can :read, :all
can :create, Post
can :manage, Post do |post|
post.try(:user) == user
end
else
can :read, :all
can :create, Comment
end
end
end
role? 方法需要自己实现
#####几个权限action :read 对应 index show :update 对应 edit :create 对应 new
#####Example
can :manage, Article # user can perform any action on the article
can :read, :all # user can read any object
can :manage, :all # user can perform any action on any object
can [:update, :destroy], [Article, Comment] #对Article, Comment有修改,删除的权限
####使用
#####在controller中,对局部资源的权限认证 authorize!
def edit
@post = Post.find(params[:id])
authorize! :update, @post
end
#####整个controller需要权限认证,在controller中添加 load_and_authorize_resource
#####若无权限,则处理异常 如下:
一般添加到application_controller里, 也可添加到一般controller
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, :alert => exception.message
end
如果想保证所有资源的每一个action都需要认证,则可以在ApplicationController
中加入check_authorization
如果某些从applicationController
继承的controller要跳过认证添加skip_authorization_check
即可
当然也有对view的处理如下示例:
<% if can? :destroy, post %>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<% end %>
<% if can? :destroy, post %>
<td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
本文参考:
https://github.com/ryanb/cancan
https://github.com/ryanb/cancan/wiki/defining-abilities
http://blog.163.com/fuhaocn@126/blog/static/36665080201342011835355/