(编辑:jimmy 日期: 2025/10/29 浏览:2)
本文实例讲述了thinkPHP5框架auth权限控制类。分享给大家供大家参考,具体如下:
这个是比较简单的用法:
直接把类贴出来,这里我改了,我没有用uid,因为我建的表是admin表,所以代码里对应查询改成了aid
还有表名,我都去掉了前缀
<","隔开,status 状态:为1正常,为0禁用
-- ----------------------------
DROP TABLE IF EXISTS `auth_group`;
CREATE TABLE `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;
-- ----------------------------
-- group_access 用户组明细表
-- uid:用户id,group_id:用户组id
-- ----------------------------
DROP TABLE IF EXISTS `group_access`;
CREATE TABLE `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' => 'auth_group', // 用户组数据表名
'auth_group_access' => 'group_access', // 用户-用户组关系表
'auth_rule' => 'auth_rule', // 权限规则表
'auth_user' => 'admin' // 用户信息表
);
public function __construct() {
if (config('auth_config')) {
//可设置配置项 auth_config, 此配置项为数组。
$this->_config = array_merge($this->_config, config('auth_config'));
}
}
/**
* 检查权限
* @param name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
* @param uid int 认证用户的id
* @param string mode 执行check的模式
* @param relation string 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
* @return boolean 通过验证返回true;失败返回false
*/
public function check($name, $uid, $type=1, $mode='url', $relation='or') {
if (!$this->_config['auth_on'])
return true;
$authList = $this->getAuthList($uid,$type); //获取用户需要验证的所有有效规则列表
if (is_string($name)) {
$name = strtolower($name);
if (strpos($name, ',') !== false) {
$name = explode(',', $name);
} else {
$name = array($name);
}
}
$list = array(); //保存验证通过的规则名
if ($mode=='url') {
$REQUEST = unserialize( strtolower(serialize($_REQUEST)) );
}
foreach ( $authList as $auth ) {
$query = preg_replace('/^.+\" g", "g.id=a.group_id")
->where("a.aid='$uid' and g.status='1'")
->field('aid,group_id,title,rules')->select();
$groups[$uid] = $user_groups "color: #0000ff">extend下面的auth目录里,命名空间为auth
然后在使用的控制器中使用构造方法,或者继承一个使用了构造方法的控制器,构造方法如下:
public function _initialize()
{
$aid = 1;
$auth = new \auth\Auth();
$request = Request::instance();
$au = $auth->check($request->module() . '/' . $request->controller() . '/' . $request->action(), $aid);
if (!$au) {// 第一个参数是规则名称,第二个参数是用户UID
/* return array('status'=>'error','msg'=>'有权限!');*/
$this->error('你没有权限');
}
}
上面的$aid应该是用户登录以后获取的,正常情况下应该是session()获取的用户id
相关业务逻辑可以自行判断,剩下的就是添加全县,用户组添加啊,等等系列增删改查了。
更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技术总结》。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。