管理员权限的操作方法

原创2019-01-04 15:13:35200
摘要:总结:在Base.php控制器里实现管理员权限控制,判断用户是否有权限,还有课访问的菜单,如果没有权限,会提示无法访问,如果有权限可以进行操作,通过查询这个账号的gid对应的权限表的gid进行查询。/************************  Base.php  *******************************/<?phpnamespace app\

总结:在Base.php控制器里实现管理员权限控制,判断用户是否有权限,还有课访问的菜单,如果没有权限,会提示无法访问,如果有权限可以进行操作,通过查询这个账号的gid对应的权限表的gid进行查询。

/************************  Base.php  *******************************/

<?php
namespace app\admins\controller;
use think\Controller;
use Util\SysDb;

class Base extends Controller{
  public function __construct(){
     parent::__construct();
     $this->_admin = session('admin');
     if(!$this->_admin){
        header('Location:/index.php/admins/account/login');
        exit;
     }
     $this->assign('admin',$this->_admin);
     $this->db = new SysDb;
     // 判断用户是否有权限
     $group = $this->db->table('admin_groups')->where(array('gid'=>$this->_admin['gid']))->item();
     if(!$group){
        $this->request_error('对不起,您没有权限');
     }
     $rights = json_decode($group['rights']);
     // 当前访问的菜单
     $controller = request()->controller();
     $method = request()->action();
     $res = $this->db->table('admin_menus')->where(array('controller'=>$controller,'method'=>$method))->item();
     if(!$res){
        $this->request_error('对不起,您访问的功能不存在');
     }
     if($res['status'] == 1){
        $this->request_error('对不起,该功能已禁止使用');
     }
     if(!in_array($res['mid'],$rights)){
        $this->request_error('对不起,您没有权限');
     }

  }

  private function request_error($msg){
     if(request()->isAjax()){
        exit(json_encode(array('code'=>1,'msg'=>$msg)));
     }
     exit($msg);
  }

}


/****************************   Home.php ***************************/

<?php
namespace app\admins\controller;
use think\Controller;
use Util\SysDb;

class Home extends Base{

   public function index(){
      $role = $this->db->table('admin_groups')->where(array('gid'=>$this->_admin['gid']))->item();
      if($role){
         $role['rights'] = $role['rights']?json_decode($role['rights'],true):[];
      }
      if($role['rights']){
         $where = 'mid in('.implode(',', $role['rights']).') and ishidden=0 and status=0';
         $menus = $this->db->table('admin_menus')->where($where)->cates('mid');
         $menus && $menus = $this->gettreeitems($menus);
      }

      $data['menus'] = $menus;
      $data['role'] = $role;
      return $this->fetch('',$data);
  }

  public function welcome(){
     return $this->fetch();
  }

  private function gettreeitems($items){
     $tree = [];
     foreach ($items as $item) {
        if(isset($items[$item['pid']])){
           $items[$item['pid']]['children'][] = &$items[$item['mid']];
        }else{
           $tree[] = &$items[$item['mid']];
        }
     }
     return $tree;
  }
}

批改老师:查无此人批改时间:2019-01-04 15:23:00
老师总结:做的不错,思考的方向是对的。按照你的方向,可以把每个列表的按钮,也做个权限。这个有点难度。 继续加油。

发布手记

热门词条