*/ namespace app\admin\behavior; use app\model\AdminAuthGroup; use app\model\AdminAuthGroupAccess; use app\model\AdminAuthRule; use app\util\ReturnCode; use app\util\Tools; use think\Request; class ApiPermission { /** * 用户权限检测 * @return \think\response\Json * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\ModelNotFoundException * @throws \think\exception\DbException * @author zhaoxiang */ public function run() { $request = Request::instance(); $route = $request->param(); $header = config('apiAdmin.CROSS_DOMAIN'); $ApiAuth = $request->header('ApiAuth', ''); $userInfo = cache('Login:' . $ApiAuth); $userInfo = json_decode($userInfo, true); if (!$this->checkAuth($userInfo['id'], $route)) { $data = ['code' => ReturnCode::INVALID, 'msg' => '非常抱歉,您没有权限这么做!', 'data' => []]; return json($data, 200, $header); } } /** * 检测用户权限 * @param $uid * @param $route * @return bool * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\ModelNotFoundException * @throws \think\exception\DbException * @author zhaoxiang */ private function checkAuth($uid, $route) { $isSupper = Tools::isAdministrator($uid); if (!$isSupper) { $keys = array_keys($route); $rules = $this->getAuth($uid); $baseUrl = $keys[0]; if(isset($rules[$baseUrl])){ if($rules[$baseUrl]['all']==1){ return true; }else{ $intersect = array_intersect_assoc($route,$rules[$baseUrl]['query']); if(sizeof(array_diff_assoc($rules[$baseUrl]['query'],$intersect))==0){ return true; }else{ return false; } } }else{ return false; } } else { return true; } } /** * 根据用户ID获取全部权限节点 * @param $uid * @return array * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\ModelNotFoundException * @throws \think\exception\DbException * @author zhaoxiang */ private function getAuth($uid) { $groups = AdminAuthGroupAccess::get(['uid' => $uid]); if (isset($groups) && $groups->groupId) { $openGroup = (new AdminAuthGroup())->whereIn('id', $groups->groupId)->where(['status' => 1])->select(); if (isset($openGroup)) { $openGroupArr = []; foreach ($openGroup as $group) { $openGroupArr[] = $group->id; } $allRulesUrl = (new AdminAuthRule())->whereIn('groupId', $openGroupArr)->column('url'); if (isset($allRulesUrl)) { $rules = []; foreach ($allRulesUrl as $rule) { $query = parse_url($rule); $route = '/'.$query['path']; if(!isset($query['query'])){ $rules[$route]['all'] = 1; }else{ parse_str($query['query'],$query_arr); $rules[$route]['all'] = 0; $rules[$route]['query'] = $query_arr; } } $rules = array_unique($rules); return $rules; } else { return []; } } else { return []; } } else { return []; } } }