比RBAC更好的权限认证方式(Auth类认证)

Auth 类已经在ThinkPHP代码仓库中存在很久了,但是因为一直没有出过它的教程, 很少人知道它, 它其实比RBAC更方便 。

RBAC是按节点进行认证的,如果要控制比节点更细的权限就有点困难了,比如页面上面的操作按钮, 我想判断用户权限来显示这个按钮, 如果没有权限就不会显示这个按钮; 再比如我想按积分进行权限认证, 积分在0-100时能干什么, 在101-200时能干什么。 这些权限认证用RABC都很困难。
下面介绍 Auth权限认证, 它几乎是全能的, 除了能进行节点认证, 上面说的RABC很难认证的两种情况,它都能实现。
Auth权限认证是按规则进行认证。我先说说它的原理。 在数据库中我们有 规则表(think_auth_rule) ,用户组表(think_auth_group), 用户组明显表(think_auth_group_access)
我们在规则表中定义权限规则 , 在用户组表中定义每个用户组有哪些权限规则,在用户组明显表中 定义用户所属的用户组。 下面举例说明。
我们要判断用户是否有显示一个操作按钮的权限, 首先定义一个规则, 在规则表中添加一个名为 show_button 的规则。 然后在用户组表添加一个用户组,定义这个用户组有show_button 的权限规则(think_auth_group表中rules字段存得时规则ID,多个以逗号隔开), 然后在用户组明细表定义 UID 为1 的用户 属于刚才这个的这个用户组。
ok,表数据定义好后, 判断权限很简单

1
2
3
4
5
6
7
 import('ORG.Util.Auth');//加载类库
$auth=new Auth();
if($auth->check('show_button',1)){// 第一个参数是规则名称,第二个参数是用户UID
//有显示操作按钮的权限
}else{
//没有显示操作按钮的权限
}

Auth类同样可以做像RBAC一样的对节点进行认证。 我们只要将规则名称,定义为节点名称就行了。
和RABC一样 在公共控制器CommonAction 中定义_initialize 方法,

1
2
3
4
5
6
7
8
9
10
<?php
class CommonAction extends Action{
public function _initialize(){
import('ORG.Util.Auth');//加载类库
$auth=new Auth();
if(!$auth->check(MODULE_NAME.'-'.ACTION_NAME,session('uid'))){
$this->error('你没有权限');
}
}
}

这时候我们可以在数据库中添加的节点规则, 格式为: “控制器名称-方法名称”

Auth 类 还可以多个规则一起认证 如:

1
$auth->check('rule1,rule2',uid); 

表示 认证用户只要有rule1的权限或rule2的权限,只要有一个规则的权限,认证返回结果就为true 即认证通过。 默认多个权限的关系是 “or” 关系,也就是说多个权限中,只要有个权限通过则通过。 我们也可以定义为 “and” 关系

1
$auth->check('rule1,rule2',uid,'and'); 

第三个参数指定为”and” 表示多个规则以and关系进行认证, 这时候多个规则同时通过认证 才有权限。只要一个规则没有权限则就会返回false。

Auth认证,一个用户可以属于多个用户组。 比如我们对 show_button这个规则进行认证, 用户A 同时属于 用户组1 和用户组2 两个用户组 , 用户组1 没有show_button 规则权限, 但如果用户组2 有show_button 规则权限,则一样会权限认证通过。

1
$auth->getGroups(uid)

通过上面代码,可以获得用户所属的所有用户组,方便我们在网站上面显示。

Auth类还可以按用户属性进行判断权限, 比如 按照用户积分进行判断, 假设我们的用户表 (think_members) 有字段 score 记录了用户积分。
我在规则表添加规则时,定义规则表的condition 字段,condition字段是规则条件, 默认为空 表示没有附加条件, 用户组中只有规则 就通过认证。 如果定义了 condition字段, 用户组中有规则 不一定能通过认证, 程序还会判断是否满足 附加条件。 比如我们添加几条规则:
name字段: grade1 , condition字段: {score}<100
name字段: grade2, condition字段: {score}>100 and {score}<200
name 字段: grade3, condition字段 : {score}>200 and {score}<300

这里 {score} 表示 think_members 表 中字段 score的值。

那么这时候
$auth->check(‘grade1’,uid) 是判断用户积分是不是0-100
$auth->check(‘grade2’,uid) 判断用户积分是不是在100-200
$auth->check(‘grade3’,uid) 判断用户积分是不是在200-300

Auth 类认证的使用方法 大致如上,是否有点相见恨晚的感觉?

-—————————————————

在使用Auth类前需要配置config.php

1
2
3
4
5
6
7
8
'AUTH_CONFIG'=>array(
'AUTH_ON' => true, //认证开关
'AUTH_TYPE' => 1, // 认证方式,1为时时认证;2为登录认证。
'AUTH_GROUP' => 'think_auth_group', //用户组数据表名
'AUTH_GROUP_ACCESS' => 'think_auth_group_access', //用户组明细表
'AUTH_RULE' => 'think_auth_rule', //权限规则表
'AUTH_USER' => 'think_members'//用户信息表
)

需要导入数据库

mysql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
-- ----------------------------
-- think_auth_rule,规则表,
-- id:主键,name:规则唯一标识, title:规则中文名称 status 状态:为1正常,为0禁用,condition:规则表达式,为空表示存在就验证,不为空表示按照条件验证
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_rule`;
CREATE TABLE `think_auth_rule` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`name` char(80) NOT NULL DEFAULT '',
`title` char(20) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`condition` char(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group 用户组表,
-- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则","隔开,status 状态:为1正常,为0禁用
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group`;
CREATE TABLE `think_auth_group` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` char(100) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`rules` char(80) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group_access 用户组明细表
-- uid:用户id,group_id:用户组id
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group_access`;
CREATE TABLE `think_auth_group_access` (
`uid` mediumint(8) unsigned NOT NULL,
`group_id` mediumint(8) unsigned NOT NULL,
UNIQUE KEY `uid_group_id` (`uid`,`group_id`),
KEY `uid` (`uid`),
KEY `group_id` (`group_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

最后需要下载Auth类文件到你的项目中,大家可以下载我上传的附件, Auth类在ThinkPHP代码仓库中的位置在:https://github.com/liu21st/extend/blob/master/Extend/Library/ORG/Util/Auth.class.php

为防止某些用户无法访问,直接将该文件源码贴出来:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <weibo.com/luofei614> 
// +----------------------------------------------------------------------
/**
* 权限认证类
* 功能特性:
* 1,是对规则进行认证,不是对节点进行认证。用户可以把节点当作规则名称实现对节点进行认证。
* $auth=new Auth(); $auth->check('规则名称','用户id')
* 2,可以同时对多条规则进行认证,并设置多条规则的关系(or或者and)
* $auth=new Auth(); $auth->check('规则1,规则2','用户id','and')
* 第三个参数为and时表示,用户需要同时具有规则1和规则2的权限。 当第三个参数为or时,表示用户值需要具备其中一个条件即可。默认为or
* 3,一个用户可以属于多个用户组(think_auth_group_access表 定义了用户所属用户组)。我们需要设置每个用户组拥有哪些规则(think_auth_group 定义了用户组权限)
*
* 4,支持规则表达式。
* 在think_auth_rule 表中定义一条规则时,如果type为1, condition字段就可以定义规则表达式。 如定义{score}>5 and {score}<100 表示用户的分数在5-100之间时这条规则才会通过。
* @category ORG
* @package ORG
* @subpackage Util
* @author luofei614<weibo.com/luofei614>
*/

//数据库
/*
-- ----------------------------
-- think_auth_rule,规则表,
-- id:主键,name:规则唯一标识, title:规则中文名称 status 状态:为1正常,为0禁用,condition:规则表达式,为空表示存在就验证,不为空表示按照条件验证
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_rule`;
CREATE TABLE `think_auth_rule` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`name` char(80) NOT NULL DEFAULT '',
`title` char(20) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`condition` char(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group 用户组表,
-- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则","隔开,status 状态:为1正常,为0禁用
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group`;
CREATE TABLE `think_auth_group` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` char(100) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`rules` char(80) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group_access 用户组明细表
-- uid:用户id,group_id:用户组id
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group_access`;
CREATE TABLE `think_auth_group_access` (
`uid` mediumint(8) unsigned NOT NULL,
`group_id` mediumint(8) unsigned NOT NULL,
UNIQUE KEY `uid_group_id` (`uid`,`group_id`),
KEY `uid` (`uid`),
KEY `group_id` (`group_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/

class Auth{

//默认配置
protected $_config = array(
'AUTH_ON' => true, //认证开关
'AUTH_TYPE' => 1, // 认证方式,1为时时认证;2为登录认证。
'AUTH_GROUP' => 'think_auth_group', //用户组数据表名
'AUTH_GROUP_ACCESS' => 'think_auth_group_access', //用户组明细表
'AUTH_RULE' => 'think_auth_rule', //权限规则表
'AUTH_USER' => 'think_members'//用户信息表
);

public function __construct() {
if (C('AUTH_CONFIG')) {
//可设置配置项 AUTH_CONFIG, 此配置项为数组。
$this->_config = array_merge($this->_config, C('AUTH_CONFIG'));
}
}

//获得权限$name 可以是字符串或数组或逗号分割, uid为 认证的用户id, $or 是否为or关系,为true是, name为数组,只要数组中有一个条件通过则通过,如果为false需要全部条件通过。
public function check($name, $uid, $relation='or') {
if (!$this->_config['AUTH_ON'])
return true;
$authList = $this->getAuthList($uid);
if (is_string($name)) {
if (strpos($name, ',') !== false) {
$name = explode(',', $name);
} else {
$name = array($name);
}
}
$list = array(); //有权限的name
foreach ($authList as $val) {
if (in_array($val, $name))
$list[] = $val;
}
if ($relation=='or' and !empty($list)) {
return true;
}
$diff = array_diff($name, $list);
if ($relation=='and' and empty($diff)) {
return true;
}
return false;
}

//获得用户组,外部也可以调用
public function getGroups($uid) {
static $groups = array();
if (isset($groups[$uid]))
return $groups[$uid];
$user_groups = M()->table($this->_config['AUTH_GROUP_ACCESS'] . ' a')->where("a.uid='$uid' and g.status='1'")->join($this->_config['AUTH_GROUP']." g on a.group_id=g.id")->select();
$groups[$uid]=$user_groups?$user_groups:array();
return $groups[$uid];
}

//获得权限列表
protected function getAuthList($uid) {
static $_authList = array();
if (isset($_authList[$uid])) {
return $_authList[$uid];
}
if(isset($_SESSION['_AUTH_LIST_'.$uid])){
return $_SESSION['_AUTH_LIST_'.$uid];
}
//读取用户所属用户组
$groups = $this->getGroups($uid);
$ids = array();
foreach ($groups as $g) {
$ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
}
$ids = array_unique($ids);
if (empty($ids)) {
$_authList[$uid] = array();
return array();
}
//读取用户组所有权限规则
$map=array(
'id'=>array('in',$ids),
'status'=>1
);
$rules = M()->table($this->_config['AUTH_RULE'])->where($map)->select();
//循环规则,判断结果。
$authList = array();
foreach ($rules as $r) {
if (!empty($r['condition'])) {
//条件验证
$user = $this->getUserInfo($uid);
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $r['condition']);
//dump($command);//debug
@(eval('$condition=(' . $command . ');'));
if ($condition) {
$authList[] = $r['name'];
}
} else {
//存在就通过
$authList[] = $r['name'];
}
}
$_authList[$uid] = $authList;
if($this->_config['AUTH_TYPE']==2){
//session结果
$_SESSION['_AUTH_LIST_'.$uid]=$authList;
}
return $authList;
}
//获得用户资料,根据自己的情况读取数据库
protected function getUserInfo($uid) {
static $userinfo=array();
if(!isset($userinfo[$uid])){
$userinfo[$uid]=M()->table($this->_config['AUTH_USER'])->find($uid);
}
return $userinfo[$uid];
}

}

文章来源:https://www.thinkphp.cn/topic/4029.html