| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427 |
- <?php
- /**
- * 角色管理控制器
- *
- * Created by PhpStorm.
- * User: edison
- * Date: 2018/3/26
- * Time: 上午11:50
- */
- namespace app\admin\controller;
- use think\Db;
- use tree\Tree;
- class Rbac extends Admin
- {
- public function _initialize() {
- parent::_initialize();
- $this->adminAuthRuleModel = Db::name('nw_admin_auth_rule');
- $this->adminRoleModel = Db::name('nw_admin_role');
- $this->adminRoleUserModel = Db::name('nw_admin_role_user');
- }
- public function index()
- {
- $where = [];
- $role_id = 0;
- //非超级管理员时
- if(!in_array(session('ADMIN_ID') ,[1,19])){
- $role_id = $this->adminRoleUserModel->where(['user_id'=>session('ADMIN_ID')])->value('role_id');
- }
- $data = $this->adminRoleModel->field('id,parent_id,name,status,create_time,remark')->order('id')->select();
- $tree = new Tree();
- $tree->init($data);
- $childrenlist = $tree->getTreeList($tree->getTreeArrayO($role_id));
- $this->assign("roles", $childrenlist);
- return $this->fetch();
- }
- public function roleAdd()
- {
- $role_id = (int)$this->request->param("id", 0, 'intval');
- if (!$role_id && !in_array(session('ADMIN_ID') ,[1,19]) ) {
- $role_id = $this->adminRoleUserModel->where(['user_id'=>session('ADMIN_ID')])->value('role_id');
- }
- if ( $role_id) {
- $name = $this->adminRoleModel->where('id',$role_id)->value('name');
- }else{
- $name = '最高管理员';
- }
- $this->assign("role_id", $role_id);
- $this->assign("name", $name);
- return $this->fetch('roleadd');
- }
- public function roleAddPost()
- {
- if ($this->request->isPost()) {
- $result = $this->validate($_POST, 'Role');
- if ($result !== true) {
- // 验证失败 输出错误信息
- $this->error($result);
- } else {
- $_POST['update_time'] = $_POST['create_time'] = time();
- if ( !empty($_POST['remark']) && strlen($_POST['remark']) > 200) {
- $_POST['remark'] = substr($_POST['remark'], 0, 200);
- }
- // 判断用户是否有权限
- $res = $this->_isPermission($_POST['parent_id']);
- if ( !$res) {
- $this->error("添加角色失败,没有权限");
- }
- $result = $this->adminRoleModel->insert($_POST);
- if ($result) {
- $statusStr = $_POST['status'] ? '启用' : '禁用';
- $LogStr = "新增角色:" .$_POST['name']. ",状态:" . $statusStr;
- $this->insertLog($this->current_node,$LogStr,162);
- $this->success("添加角色成功", url("rbac/index"));
- } else {
- $this->error("添加角色失败");
- }
- }
- }
- }
- public function roleEdit()
- {
- $id = $this->request->param("id", 0, 'intval');
- $data = $this->adminRoleModel->where(["id" => $id])->find();
- if (!$data) {
- $this->error("该角色不存在!");
- }
- if ( $data['parent_id']) {
- $data['parent_name'] = $this->adminRoleModel->where('id',$data['parent_id'])->value('name');
- }else{
- $data['parent_name'] = '最高管理员';
- }
- $this->assign("data", $data);
- return $this->fetch('roleedit');
- }
- public function roleEditPost()
- {
- $id = $this->request->param("id", 0, 'intval');
- if (empty($id)) {
- $this->error("角色id不能为空!");
- }
- if ($this->request->isPost()) {
- $result = $this->validate($_POST, 'Role');
- if ($result !== true) {
- // 验证失败 输出错误信息
- $this->error($result);
- } else {
- if ( !empty($_POST['remark']) && strlen($_POST['remark']) > 200) {
- $_POST['remark'] = substr($_POST['remark'], 0, 200);
- }
- $data = [
- 'id' => $id,
- 'name' => $_POST['name'],
- 'status' => $_POST['status'],
- 'remark' => $_POST['remark'],
- 'update_time' => time(),
- ];
- if ($this->adminRoleModel->update($data) !== false) {
- $statusStr = $_POST['status'] ? '启用' : '禁用';
- $LogStr = "编辑角色:" .$_POST['name']. ",状态:" . $statusStr;
- $this->insertLog($this->current_node,$LogStr,162);
- $this->success("保存成功!", url('rbac/index'));
- } else {
- $this->error("保存失败!");
- }
- }
- }
- }
- public function roleDelete()
- {
- $id = (int)$this->request->param("id", 0, 'intval');
- $type = (int)$this->request->param("type", 0, 'intval');
- if (empty($id)) {
- $this->error("角色id不能为空!");
- }
- $data = $this->adminRoleModel->field('id,parent_id,name')->order('id')->select();
- $tree = new Tree();
- $tree->init($data);
- $childrenlist = $tree->getChildrenIds($id,true);
- $count = $this->adminRoleUserModel->where(['role_id' => ['in', $childrenlist]])->count();
- if ($count > 0) {
- $this->error("当前角色或其下级角色里有用户,无法删除!");
- } else {
- if ( !$type && count($childrenlist) > 1) {
- $this->success("是否删除该角色?删除后它的所有下级角色也将被删除!");
- }
- $name = $this->adminRoleModel->where('id',$id)->value('name');
- $status = $this->adminRoleModel->delete($childrenlist);
- if (!empty($status)) {
- $nameStr = count($childrenlist) > 1 ? $name . '及其下级角色' : $name;
- $LogStr = "删除角色:" . $nameStr;
- $this->insertLog($this->current_node,$LogStr,162);
- $this->success("删除成功!", url('rbac/index'));
- } else {
- $this->error("删除失败!");
- }
- }
- }
- /**
- * 权限设置页
- * @return mixed|string
- */
- public function authorize()
- {
- //角色ID
- $roleId = $this->request->param("id", 0, 'intval');
- if (empty($roleId)) {
- $this->error("参数错误!");
- }
- $tree = new Tree();
- $tree->icon = ['│ ', '├─ ', '└─ '];
- $tree->nbsp = ' ';
- $newMenus = [];
- //当前角色信息
- $authInfo = $this->adminRoleModel->field('auth_ids,parent_id,name')->where(["id" => $roleId])->find();
- $authIdsArr = explode(',', $authInfo['auth_ids']);
- if($authInfo['parent_id']>0)
- {
- //父级角色信息
- $parentRoleInfo = $this->adminRoleModel->field('auth_ids')->where(["id" => $authInfo['parent_id']])->find();
- //总的菜单树
- $result = $this->adminAuthRuleModel->where(['id'=>['in',$parentRoleInfo['auth_ids']]])->select();
- }
- else{
- //总的菜单树
- $result = $this->adminAuthRuleModel->select();
- }
- $privilegeData = $this->adminAuthRuleModel->where('id', 'in', $authIdsArr)->column('auth_name');
- foreach ($result as $m) {
- $newMenus[$m['id']] = $m;
- }
- foreach ($result as $n => $t) {
- $result[$n]['checked'] = ($this->_isChecked($t, $privilegeData)) ? ' checked' : '';
- $result[$n]['level'] = $this->_getLevel($t['id'], $newMenus);
- $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;';
- $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';
- }
- $str = "<tr id='node-\$id'\$parentIdNode style='\$style'>
- <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuId[]' value='\$id' lay-skin='primary' level='\$level' \$checked lay-filter='filter'> \$name</td>
- </tr>";
- $tree->init($result);
- $category = $tree->getTree(0, $str);
- $category = "<td style='padding-left:30px;'> ".$authInfo['name']."</td>" . $category;
- $this->assign("category", $category);
- $this->assign("roleId", $roleId);
- return $this->fetch();
- }
- /**
- * 权限设置提交处理
- * @return mixed|string
- */
- public function authorizePost()
- {
- if ($this->request->isPost()) {
- $roleId = $this->request->param("roleId", 0, 'intval');
- if (!$roleId) {
- $this->error("需要授权的角色不存在!");
- }
- if (is_array($this->request->param('menuId/a')) && count($this->request->param('menuId/a')) > 0) {
- //旧的权限ID集
- $old_auth_ids = $this->adminRoleModel->where(["id" => $roleId])->value('auth_ids');
- $authIds = implode(',', array_filter($_POST['menuId'], function($menuId){
- return $this->adminAuthRuleModel->where(["id" => $menuId])->field("id")->find();
- }));
- // 启动事务
- Db::startTrans();
- try{
- $this->adminRoleModel->where(["id" => $roleId])->update(['auth_ids' => $authIds]);
- if(!empty($old_auth_ids)){
- $this->_updateChildRoleAuth($roleId,$old_auth_ids,$authIds);
- }
- // 提交事务
- Db::commit();
- }
- catch (\Exception $e) {
- // 回滚事务
- Db::rollback();
- $this->error("授权失败!".$e->getMessage());
- }
- $this->success("授权成功!", 'rbac/index');
- } else {
- //当没有数据时,清除当前角色授权
- $this->adminRoleModel->where(["id" => $roleId])->update(['auth_ids' => '']);
- $this->error("没有接收到数据,执行清除授权成功!");
- }
- }
- }
- /**
- * 更新下级角色权限
- *
- * @param $roleId int 当前角色ID
- * @param $old_auth_ids string 更新前的权限ID集
- * @param $authIds string 变更后的权限ID集
- *
- */
- private function _updateChildRoleAuth($roleId,$old_auth_ids, $authIds)
- {
- //本次修改被减少的权限ID集
- $diffAuthIds = array_diff(explode(',',$old_auth_ids), explode(',',$authIds));
- //查询下级角色
- while ($info = $this->adminRoleModel->field('id,auth_ids')->whereIn('parent_id', $roleId)->select()) {
- $tmp = [];
- if (!empty($info)) {
- foreach ($info as $v) {
- if(!empty($v['auth_ids']))
- {
- $tmp_auth_ids = array_diff(explode(',',$v['auth_ids']),$diffAuthIds);
- $this->adminRoleModel->where(['id'=>$v['id']])->update(['auth_ids'=>implode(',',$tmp_auth_ids)]);
- }
- $tmp[] = $v['id'];
- }
- $roleId = $tmp;
- }
- }
- }
- /**
- * 检查指定菜单是否有权限
- * @param array $menu menu表中数组
- * @param $privData
- * @return bool
- */
- private function _isChecked($menu, $privData)
- {
- if ($privData) {
- if (in_array($menu['auth_name'], $privData)) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
- /**
- * 获取菜单深度
- * @param $id
- * @param array $array
- * @param int $i
- * @return int
- */
- protected function _getLevel($id, $array = [], $i = 0)
- {
- if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) {
- return $i;
- } else {
- $i++;
- return $this->_getLevel($array[$id]['parent_id'], $array, $i);
- }
- }
- // 判断用户是否有角色权限
- private function _isPermission($id)
- {
- // 超级管理员时
- if(in_array(session('ADMIN_ID') ,[1,19])){
- return true;
- }
- $role_id = $this->adminRoleUserModel->where(['user_id'=>session('ADMIN_ID')])->value('role_id');
- $data = $this->adminRoleModel->field('id,parent_id,name')->order('id')->select();
- $tree = new Tree();
- $tree->init($data);
- $childrenlist = $tree->getChildrenIds($role_id,true);
- return in_array($id,$childrenlist) ? true : false;
- }
- }
|