thinkphp6 权限管理

  1. composer require wenhainan/thinkphp6-auth

  2. 配置

// auth配置 自定义数据表位置在 ./config/auth.php里面
[
'auth_on' => 1, // 权限开关 1开启;0关闭
'auth_type' => 1, // 认证方式,1为实时认证;2为登录认证。
'auth_group' => 'think_auth_group', // 用户组数据不带前缀表名
'auth_group_access' => 'think_auth_group_access', // 用户-用户组关系不带前缀表名
'auth_rule' => 'think_auth_rule', // 权限规则不带前缀表名
'auth_user' => 'user', // 用户信息表不带前缀表名,主键自增字段为id
],

  1. 导入数据
-----`think_` 为自定义的数据表前缀-----------
----------------------------------------------
-- 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;
  1. 使用
// 引入类库
use think\wenhainan\Auth;

// 获取auth实例
$auth = Auth::instance();

// 检测权限
if($auth->check('show_button',1)){// 第一个参数是规则名称,第二个参数是用户UID
    //有显示操作按钮的权限
}else{
    //没有显示操作按钮的权限
}

<?php
namespace app\admin\controller;
 
use app\BaseController;
use think\facade\View;
use think\wenhainan\Auth;
 
class AdminBase extends BaseController
{
    public function initialize()
    {
        $controller = strtolower(request()->controller());
        $action     = strtolower(request()->action());
        $auth       = Auth::instance();
        // dump($auth);exit;
        // 检测权限
        if(!$auth->check($controller.'-'.$action,1)){// 第一个参数是规则名称,第二个参数是用户UID
            //有显示操作按钮的权限
           dump('您没有权限访问');
        }        
    }
}

image

  • 在Auth.php文件里注释掉 ['type','=',$type]
  • 注释@eval 修改为
    $condition = $command;
  1. 数据表配置

image
6.
image
image
image

image

posted @ 2021-10-25 11:24  子岚天羽卿怜水  阅读(844)  评论(0编辑  收藏  举报