rails使用Devise + CanCanCan + rolify 登录+ 权限控制+角色
1.编辑 Gemfile
增加 Devise, CanCanCan and rolify gems:
gem 'devise' gem 'cancancan' gem 'rolify'
-
终端输入
bundle install
-
Devise generator
# rails generate devise:install
- 创建 User model from Devise
# rails generate devise User
- 创建Ability.rb model from CanCanCan
# rails generate cancan:ability
- 创建Role class from rolify
# rails generate rolify Role User
- Run migrations
# rake db:migrate
注意:当出现bug: ArgumentError: Unknown key: :optional. Valid keys are: :class_name, :class, :foreign_key, :validate, :autosave, :remote, :dependent, :primary_key, :inverse_of, :foreign_type, :polymorphic, :touch, :counter_cache
解决方法: 将 role.rb中:
:optional => true 删掉。 这是给rails 5用的东西。
1. rolify封装了一些方法,可以给每个用户添加角色 add_role , 删除角色 remove_role 等待 :
user = User.find(1) user.add_role :admin # sets a global role user.has_role? :admin => true
2. cancancan 所有的权限控制都放在, ability.rb 文件中:
class Ability
include CanCan::Ability
def initialize(user)
if user.blank?
cannot :manage, :all
####超级管理员权限####
elsif user.has_role? :admin
can :manage, :all
elsif user.has_role? "仓库管理员"
can :storehouse, DinnerTable
can :read, DinnerTable
else
can :read, :all
end
end
3.然后再view层面添加:
<% if can? :manage, :all %>
这个就表示 只有权限为manage才能进行所有的操作。
4.增加报错提示。我们可以在ApplicationController里定义:
#增加报错提示,这时如果用户进入到权限之外的网址,就会被导至root path,并且看到相应报错了。
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_path, :alert => exception.message
end
对于这个cancancan 这三篇文章看完,估计就差不多了:
参考文章:https://blog.joshsoftware.com/2012/10/23/dynamic-roles-and-permissions-using-cancan/
github: https://github.com/RolifyCommunity/rolify/wiki/Devise---CanCanCan---rolify-Tutorial
完整的博客:http://ccaloha.cc/blog/2014/06/30/dynamic-roles-and-permissions-management-using-cancan/