Rbac.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. /**
  3. * 角色管理控制器
  4. *
  5. * Created by PhpStorm.
  6. * User: edison
  7. * Date: 2018/3/26
  8. * Time: 上午11:50
  9. */
  10. namespace app\admin\controller;
  11. use think\Db;
  12. use tree\Tree;
  13. class Rbac extends Admin
  14. {
  15. public function _initialize() {
  16. parent::_initialize();
  17. $this->adminAuthRuleModel = Db::name('nw_admin_auth_rule');
  18. $this->adminRoleModel = Db::name('nw_admin_role');
  19. $this->adminRoleUserModel = Db::name('nw_admin_role_user');
  20. }
  21. public function index()
  22. {
  23. $where = [];
  24. $role_id = 0;
  25. //非超级管理员时
  26. if(!in_array(session('ADMIN_ID') ,[1,19])){
  27. $role_id = $this->adminRoleUserModel->where(['user_id'=>session('ADMIN_ID')])->value('role_id');
  28. }
  29. $data = $this->adminRoleModel->field('id,parent_id,name,status,create_time,remark')->order('id')->select();
  30. $tree = new Tree();
  31. $tree->init($data);
  32. $childrenlist = $tree->getTreeList($tree->getTreeArrayO($role_id));
  33. $this->assign("roles", $childrenlist);
  34. return $this->fetch();
  35. }
  36. public function roleAdd()
  37. {
  38. $role_id = (int)$this->request->param("id", 0, 'intval');
  39. if (!$role_id && !in_array(session('ADMIN_ID') ,[1,19]) ) {
  40. $role_id = $this->adminRoleUserModel->where(['user_id'=>session('ADMIN_ID')])->value('role_id');
  41. }
  42. if ( $role_id) {
  43. $name = $this->adminRoleModel->where('id',$role_id)->value('name');
  44. }else{
  45. $name = '最高管理员';
  46. }
  47. $this->assign("role_id", $role_id);
  48. $this->assign("name", $name);
  49. return $this->fetch('roleadd');
  50. }
  51. public function roleAddPost()
  52. {
  53. if ($this->request->isPost()) {
  54. $result = $this->validate($_POST, 'Role');
  55. if ($result !== true) {
  56. // 验证失败 输出错误信息
  57. $this->error($result);
  58. } else {
  59. $_POST['update_time'] = $_POST['create_time'] = time();
  60. if ( !empty($_POST['remark']) && strlen($_POST['remark']) > 200) {
  61. $_POST['remark'] = substr($_POST['remark'], 0, 200);
  62. }
  63. // 判断用户是否有权限
  64. $res = $this->_isPermission($_POST['parent_id']);
  65. if ( !$res) {
  66. $this->error("添加角色失败,没有权限");
  67. }
  68. $result = $this->adminRoleModel->insert($_POST);
  69. if ($result) {
  70. $statusStr = $_POST['status'] ? '启用' : '禁用';
  71. $LogStr = "新增角色:" .$_POST['name']. ",状态:" . $statusStr;
  72. $this->insertLog($this->current_node,$LogStr,162);
  73. $this->success("添加角色成功", url("rbac/index"));
  74. } else {
  75. $this->error("添加角色失败");
  76. }
  77. }
  78. }
  79. }
  80. public function roleEdit()
  81. {
  82. $id = $this->request->param("id", 0, 'intval');
  83. $data = $this->adminRoleModel->where(["id" => $id])->find();
  84. if (!$data) {
  85. $this->error("该角色不存在!");
  86. }
  87. if ( $data['parent_id']) {
  88. $data['parent_name'] = $this->adminRoleModel->where('id',$data['parent_id'])->value('name');
  89. }else{
  90. $data['parent_name'] = '最高管理员';
  91. }
  92. $this->assign("data", $data);
  93. return $this->fetch('roleedit');
  94. }
  95. public function roleEditPost()
  96. {
  97. $id = $this->request->param("id", 0, 'intval');
  98. if (empty($id)) {
  99. $this->error("角色id不能为空!");
  100. }
  101. if ($this->request->isPost()) {
  102. $result = $this->validate($_POST, 'Role');
  103. if ($result !== true) {
  104. // 验证失败 输出错误信息
  105. $this->error($result);
  106. } else {
  107. if ( !empty($_POST['remark']) && strlen($_POST['remark']) > 200) {
  108. $_POST['remark'] = substr($_POST['remark'], 0, 200);
  109. }
  110. $data = [
  111. 'id' => $id,
  112. 'name' => $_POST['name'],
  113. 'status' => $_POST['status'],
  114. 'remark' => $_POST['remark'],
  115. 'update_time' => time(),
  116. ];
  117. if ($this->adminRoleModel->update($data) !== false) {
  118. $statusStr = $_POST['status'] ? '启用' : '禁用';
  119. $LogStr = "编辑角色:" .$_POST['name']. ",状态:" . $statusStr;
  120. $this->insertLog($this->current_node,$LogStr,162);
  121. $this->success("保存成功!", url('rbac/index'));
  122. } else {
  123. $this->error("保存失败!");
  124. }
  125. }
  126. }
  127. }
  128. public function roleDelete()
  129. {
  130. $id = (int)$this->request->param("id", 0, 'intval');
  131. $type = (int)$this->request->param("type", 0, 'intval');
  132. if (empty($id)) {
  133. $this->error("角色id不能为空!");
  134. }
  135. $data = $this->adminRoleModel->field('id,parent_id,name')->order('id')->select();
  136. $tree = new Tree();
  137. $tree->init($data);
  138. $childrenlist = $tree->getChildrenIds($id,true);
  139. $count = $this->adminRoleUserModel->where(['role_id' => ['in', $childrenlist]])->count();
  140. if ($count > 0) {
  141. $this->error("当前角色或其下级角色里有用户,无法删除!");
  142. } else {
  143. if ( !$type && count($childrenlist) > 1) {
  144. $this->success("是否删除该角色?删除后它的所有下级角色也将被删除!");
  145. }
  146. $name = $this->adminRoleModel->where('id',$id)->value('name');
  147. $status = $this->adminRoleModel->delete($childrenlist);
  148. if (!empty($status)) {
  149. $nameStr = count($childrenlist) > 1 ? $name . '及其下级角色' : $name;
  150. $LogStr = "删除角色:" . $nameStr;
  151. $this->insertLog($this->current_node,$LogStr,162);
  152. $this->success("删除成功!", url('rbac/index'));
  153. } else {
  154. $this->error("删除失败!");
  155. }
  156. }
  157. }
  158. /**
  159. * 权限设置页
  160. * @return mixed|string
  161. */
  162. public function authorize()
  163. {
  164. //角色ID
  165. $roleId = $this->request->param("id", 0, 'intval');
  166. if (empty($roleId)) {
  167. $this->error("参数错误!");
  168. }
  169. $tree = new Tree();
  170. $tree->icon = ['│ ', '├─ ', '└─ '];
  171. $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
  172. $newMenus = [];
  173. //当前角色信息
  174. $authInfo = $this->adminRoleModel->field('auth_ids,parent_id,name')->where(["id" => $roleId])->find();
  175. $authIdsArr = explode(',', $authInfo['auth_ids']);
  176. if($authInfo['parent_id']>0)
  177. {
  178. //父级角色信息
  179. $parentRoleInfo = $this->adminRoleModel->field('auth_ids')->where(["id" => $authInfo['parent_id']])->find();
  180. //总的菜单树
  181. $result = $this->adminAuthRuleModel->where(['id'=>['in',$parentRoleInfo['auth_ids']]])->select();
  182. }
  183. else{
  184. //总的菜单树
  185. $result = $this->adminAuthRuleModel->select();
  186. }
  187. $privilegeData = $this->adminAuthRuleModel->where('id', 'in', $authIdsArr)->column('auth_name');
  188. foreach ($result as $m) {
  189. $newMenus[$m['id']] = $m;
  190. }
  191. foreach ($result as $n => $t) {
  192. $result[$n]['checked'] = ($this->_isChecked($t, $privilegeData)) ? ' checked' : '';
  193. $result[$n]['level'] = $this->_getLevel($t['id'], $newMenus);
  194. $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;';
  195. $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';
  196. }
  197. $str = "<tr id='node-\$id'\$parentIdNode style='\$style'>
  198. <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuId[]' value='\$id' lay-skin='primary' level='\$level' \$checked lay-filter='filter'> \$name</td>
  199. </tr>";
  200. $tree->init($result);
  201. $category = $tree->getTree(0, $str);
  202. $category = "<td style='padding-left:30px;'> ".$authInfo['name']."</td>" . $category;
  203. $this->assign("category", $category);
  204. $this->assign("roleId", $roleId);
  205. return $this->fetch();
  206. }
  207. /**
  208. * 权限设置提交处理
  209. * @return mixed|string
  210. */
  211. public function authorizePost()
  212. {
  213. if ($this->request->isPost()) {
  214. $roleId = $this->request->param("roleId", 0, 'intval');
  215. if (!$roleId) {
  216. $this->error("需要授权的角色不存在!");
  217. }
  218. if (is_array($this->request->param('menuId/a')) && count($this->request->param('menuId/a')) > 0) {
  219. //旧的权限ID集
  220. $old_auth_ids = $this->adminRoleModel->where(["id" => $roleId])->value('auth_ids');
  221. $authIds = implode(',', array_filter($_POST['menuId'], function($menuId){
  222. return $this->adminAuthRuleModel->where(["id" => $menuId])->field("id")->find();
  223. }));
  224. // 启动事务
  225. Db::startTrans();
  226. try{
  227. $this->adminRoleModel->where(["id" => $roleId])->update(['auth_ids' => $authIds]);
  228. if(!empty($old_auth_ids)){
  229. $this->_updateChildRoleAuth($roleId,$old_auth_ids,$authIds);
  230. }
  231. // 提交事务
  232. Db::commit();
  233. }
  234. catch (\Exception $e) {
  235. // 回滚事务
  236. Db::rollback();
  237. $this->error("授权失败!".$e->getMessage());
  238. }
  239. $this->success("授权成功!", 'rbac/index');
  240. } else {
  241. //当没有数据时,清除当前角色授权
  242. $this->adminRoleModel->where(["id" => $roleId])->update(['auth_ids' => '']);
  243. $this->error("没有接收到数据,执行清除授权成功!");
  244. }
  245. }
  246. }
  247. /**
  248. * 更新下级角色权限
  249. *
  250. * @param $roleId int 当前角色ID
  251. * @param $old_auth_ids string 更新前的权限ID集
  252. * @param $authIds string 变更后的权限ID集
  253. *
  254. */
  255. private function _updateChildRoleAuth($roleId,$old_auth_ids, $authIds)
  256. {
  257. //本次修改被减少的权限ID集
  258. $diffAuthIds = array_diff(explode(',',$old_auth_ids), explode(',',$authIds));
  259. //查询下级角色
  260. while ($info = $this->adminRoleModel->field('id,auth_ids')->whereIn('parent_id', $roleId)->select()) {
  261. $tmp = [];
  262. if (!empty($info)) {
  263. foreach ($info as $v) {
  264. if(!empty($v['auth_ids']))
  265. {
  266. $tmp_auth_ids = array_diff(explode(',',$v['auth_ids']),$diffAuthIds);
  267. $this->adminRoleModel->where(['id'=>$v['id']])->update(['auth_ids'=>implode(',',$tmp_auth_ids)]);
  268. }
  269. $tmp[] = $v['id'];
  270. }
  271. $roleId = $tmp;
  272. }
  273. }
  274. }
  275. /**
  276. * 检查指定菜单是否有权限
  277. * @param array $menu menu表中数组
  278. * @param $privData
  279. * @return bool
  280. */
  281. private function _isChecked($menu, $privData)
  282. {
  283. if ($privData) {
  284. if (in_array($menu['auth_name'], $privData)) {
  285. return true;
  286. } else {
  287. return false;
  288. }
  289. } else {
  290. return false;
  291. }
  292. }
  293. /**
  294. * 获取菜单深度
  295. * @param $id
  296. * @param array $array
  297. * @param int $i
  298. * @return int
  299. */
  300. protected function _getLevel($id, $array = [], $i = 0)
  301. {
  302. if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) {
  303. return $i;
  304. } else {
  305. $i++;
  306. return $this->_getLevel($array[$id]['parent_id'], $array, $i);
  307. }
  308. }
  309. // 判断用户是否有角色权限
  310. private function _isPermission($id)
  311. {
  312. // 超级管理员时
  313. if(in_array(session('ADMIN_ID') ,[1,19])){
  314. return true;
  315. }
  316. $role_id = $this->adminRoleUserModel->where(['user_id'=>session('ADMIN_ID')])->value('role_id');
  317. $data = $this->adminRoleModel->field('id,parent_id,name')->order('id')->select();
  318. $tree = new Tree();
  319. $tree->init($data);
  320. $childrenlist = $tree->getChildrenIds($role_id,true);
  321. return in_array($id,$childrenlist) ? true : false;
  322. }
  323. }