php项目中的RBAC权限
程序员文章站
2022-06-08 10:44:25
...
首先我们需要三张表
1.权限表
2.角色表
3.用户表
在登录的方法执行下列代码
public function index(){
$admin=D('admin');
$verify = new \Think\Verify();
if (IS_POST) {
$username=I('username');
$password=md5(I('password'));
$checkverify=I('checkverify');
$info = $admin->where(['username'=>$username])->find();
if ($verify->check($checkverify)) {
if ($info['password']==$password) {
session('id',$info['id']);
session('username',$info['username']);
$this->getpri($info['roleid']);
$this->success('登录成功...',U("Index/index"));
}else{
$this->error('用户名或密码错误!');
}
}else{
$this->error('验证码错误!');
}
return false;
}
$this->display();
}
public function getpri($roleid){
$role=D('role');
$roles=$role->find($roleid);
$pri=D('privilege');
if($roles['pri_id_list']=='*'){
session('privilege','*');
}else{
$pris=$pri->field('pri_name,CONCAT(mname,"/",cname,"/",aname)')->where("id IN({$roles['pri_id_list']})")->select();
$ret = array();
foreach ($pris as $k => $v){
$ret[]=$v['CONCAT(mname,"/",`cname`,"/",aname)'];
}
session('privilege',$ret);
}
}
构造函数
<?php
namespace Admin\Controller;
use Think\Controller;
class CommonController extends Controller {
public function __construct(){
parent::__construct();
if (!session('id')) {
$this->error('请先登录!',U('Login/index'));
}
if(MODULE_NAME=='Admin' && CONTROLLER_NAME=='Index'){
return true;
}
if(session('privilege')!='*' && !in_array(MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME,session('privilege'))){
$this->error('没有该权限!');
}
}
}