[RoR] 简单的角色权限检查插件

本文介绍了一种简单的角色和组权限验证方法,通过定义基类中的角色和组方法,并使用自定义异常进行权限检查。
代码比较简单:

module ActionController #:nodoc:

  class CheckGroupError 
< ActionControllerError #:nodoc:
    attr_reader :group_name
    def initialize(group_name)
      
@group_name = group_name
    end
  end
  
  class CheckRoleError 
< ActionControllerError #:nodoc:
    attr_reader :role_name
    def initialize(role_name)
      
@role_name = role_name
    end
  end
  
  class Base 
#:nodoc:
    def roles
      []
    end
    
    def groups
      []
    end
    
    def check_roles(
*role_args)
      role_args
.each do |role|
        check_role(role)
      end
    end
    
    def check_groups(
*group_args)
      group_args
.each do |group|
        check_group(group)
      end
    end
    
    def check_group(group)
      raise CheckGroupError
.new(group.to_s) unless groups().include?(group.to_s)
    end
    
    def check_role(role)
      raise CheckRoleError
.new(role.to_s)   unless roles().include?(role.to_s)      
    end
  end
  
end

只需要在ApplicationController中实现roles和groups这2个方法,对数据库模式没有任何限制,只要能保证这2个方法能够得到当前用户的角色和组即可。

有4个check方法可用,可任意使用一个或多个。

简单模拟测试一下:

class ApplicationController < ActionController::Base
  def roles
    
%w(add show)
  end

  def groups
    
%w(users)
  end
end

class TestController < ApplicationController
  def test1
    check_role 
:add
    render_text 
"OK"
  end

  def test2
    check_role 
:add
    check_group 
:users
    render_text 
"OK"
  end

  def test3
    check_groups 
:admin, :users
    render_text 
"OK"
  end

  def test4
    check_roles 
:add, :remove
    render_text 
"OK"
  end
end

其中,test1、test2都会成功,而test3和test4则会失败显示异常,只需要处理rescue_action把它修改为自己的显示页面即可。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值