config = array_merge($this->config, $config); } $this->options = array_merge($this->config, $options); }*/ public function __construct() { parent::__construct(); } /** * * @param array $options 参数 * @return Auth */ public static function instance($options = []) { if (is_null(self::$instance)) { self::$instance = new static($options); } return self::$instance; } /** * 获取User模型 * @return User */ public function getUser() { return $this->_user; } /** * 兼容调用user模型的属性 * * @param string $name * @return mixed */ public function __get($name) { return $this->_user ? $this->_user->$name : null; } /** * 兼容调用user模型的属性 */ public function __isset($name) { return isset($this->_user) ? isset($this->_user->$name) : false; } /** * 根据Token初始化 * * @param string $token Token * @return boolean */ public function init($token) { if ($this->_logined) { return true; } if ($this->_error) { return false; } $data = Tokencompany::get($token); if (!$data) { return false; } $user_id = intval($data['user_id']); if ($user_id > 0) { $user = User::get($user_id); if (!$user) { $this->setError('Account not exist'); return false; } if ($user['status'] != 1) { $this->setError('Account is locked'); return false; } $this->_user = $user; $this->_logined = true; $this->_token = $token; //初始化成功的事件 Hook::listen("company_init_successed", $this->_user); return true; } else { $this->setError('You are not logged in'); return false; } } /** * 用户登录 * * @param string $account 账号,用户名、邮箱、手机号 * @param string $password 密码 * @return boolean */ public function login($account, $password) { $field = 'username'; $user = User::get([$field => $account]); if (!$user) { $this->setError('Account is incorrect'); return false; } if ($user->status != 1) { $this->setError('Account is locked'); return false; } if (Config::get('pcadmin.login_failure_retry') && $user->loginfailure >= 10 && time() - $user->updatetime < 86400) { $this->setError('Please try again after 1 day'); return false; } if ($user->password != $this->getEncryptPassword($password, $user->salt)) { $user->loginfailure++; $this->setError('Password is incorrect'); return false; } //直接登录会员 return $this->direct($user->id); } /** * 退出 * * @return boolean */ public function logout() { if (!$this->_logined) { $this->setError('You are not logged in'); return false; } //设置登录标识 $this->_logined = false; //删除Token Tokencompany::delete($this->_token); //退出成功的事件 Hook::listen("user_logout_successed", $this->_user); return true; } /** * 修改密码 * @param string $newpassword 新密码 * @param string $oldpassword 旧密码 * @param bool $ignoreoldpassword 忽略旧密码 * @return boolean */ public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false) { if (!$this->_logined) { $this->setError('You are not logged in'); return false; } //判断旧密码是否正确 if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) { Db::startTrans(); try { $salt = Random::alnum(); $newpassword = $this->getEncryptPassword($newpassword, $salt); $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]); Tokencompany::delete($this->_token); //修改密码成功的事件 Hook::listen("company_changepwd_successed", $this->_user); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->setError($e->getMessage()); return false; } return true; } else { $this->setError('Password is incorrect'); return false; } } /** * 直接登录账号 * @param int $user_id * @return boolean */ public function direct($user_id) { $user = User::get($user_id); if ($user) { Db::startTrans(); try { $ip = request()->ip(); $time = time(); $user->loginfailure = 0; $user->logintime = $time; $user->loginip = $ip; $user->save(); $this->_user = $user; $this->_token = Random::uuid(); Tokencompany::set($this->_token, $user->id, $this->keeptime); $this->_logined = true; //登录成功的事件 Hook::listen("company_login_successed", $this->_user); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->setError($e->getMessage()); return false; } return true; } else { return false; } } /** * 检测是否是否有对应权限 * @param string $path 控制器/方法 * @param string $module 模块 默认为当前模块 * @return boolean */ /*public function check($path = null, $module = null) { if (!$this->_logined) { return false; } $ruleList = $this->getRuleList(); $rules = []; foreach ($ruleList as $k => $v) { $rules[] = $v['name']; } $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path); $url = strtolower(str_replace('.', '/', $url)); return in_array($url, $rules) ? true : false; }*/ public function check($name, $uid = '', $relation = 'or', $mode = 'url') { $uid = $uid ? $uid : $this->id; return parent::check($name, $uid, $relation, $mode); } /** * 检测当前控制器和方法是否匹配传递的数组 * * @param array $arr 需要验证权限的数组 * @return bool */ public function match($arr = []) { $request = Request::instance(); $arr = is_array($arr) ? $arr : explode(',', $arr); if (!$arr) { return false; } $arr = array_map('strtolower', $arr); // 是否存在 if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) { return true; } // 没找到匹配 return false; } /** * 判断是否登录 * @return boolean */ public function isLogin() { if ($this->_logined) { return true; } return false; } /** * 获取当前Token * @return string */ public function getToken() { return $this->_token; } /** * 获取会员基本信息 */ public function getUserInfo_simple() { $data = $this->_user->toArray(); $allowFields = $this->getAllowFields(); $userinfo = array_intersect_key($data, array_flip($allowFields)); $userinfo = array_merge($userinfo, Tokencompany::get($this->_token)); //追加 $userinfo['avatar'] = localpath_to_netpath($userinfo['avatar']); return $userinfo; } /** * 获取会员基本信息 */ public function getUserInfo() { $data = $this->_user->toArray(); $allowFields = $this->getAllowFields(); $userinfo = array_intersect_key($data, array_flip($allowFields)); $userinfo = array_merge($userinfo, Tokencompany::get($this->_token)); //追加 $userinfo['avatar'] = localpath_to_netpath($userinfo['avatar']); //追加公司信息 $userinfo['company'] = Db::name('company')->field('id,companyname')->where('id',$userinfo['company_id'])->find(); return $userinfo; } /** * 获取当前请求的URI * @return string */ public function getRequestUri() { return $this->requestUri; } /** * 设置当前请求的URI * @param string $uri */ public function setRequestUri($uri) { $this->requestUri = $uri; } public function getGroups($uid = null) { $uid = is_null($uid) ? $this->id : $uid; return parent::getGroups($uid); } public function getRuleList($uid = null) { $uid = is_null($uid) ? $this->id : $uid; return parent::getRuleList($uid); } public function getRuleIds($uid = null) { $uid = is_null($uid) ? $this->id : $uid; return parent::getRuleIds($uid); } //绝对不允许*管理员 public function isSuperAdmin() { // return false; return in_array('*', $this->getRuleIds()) ? true : false; } /** * 获取管理员所属于的分组ID * @param int $uid * @return array */ public function getGroupIds($uid = null) { $groups = $this->getGroups($uid); $groupIds = []; foreach ($groups as $K => $v) { $groupIds[] = (int)$v['group_id']; } return $groupIds; } /** * 取出当前管理员所拥有权限的分组 * @param boolean $withself 是否包含当前所在的分组 * @return array */ public function getChildrenGroupIds($withself = false) { //取出当前管理员所有的分组 $groups = $this->getGroups(); $groupIds = []; foreach ($groups as $k => $v) { $groupIds[] = $v['id']; } $originGroupIds = $groupIds; foreach ($groups as $k => $v) { if (in_array($v['pid'], $originGroupIds)) { $groupIds = array_diff($groupIds, [$v['id']]); unset($groups[$k]); } } // 取出所有分组 $groupList = \app\company\model\AuthGroup::where($this->isSuperAdmin() ? '1=1' : ['status' => 'normal'])->where('company_id',$this->company_id)->select(); $objList = []; foreach ($groups as $k => $v) { if ($v['rules'] === '*') { $objList = $groupList; break; } // 取出包含自己的所有子节点 $childrenList = Tree::instance()->init($groupList, 'pid')->getChildren($v['id'], true); $obj = Tree::instance()->init($childrenList, 'pid')->getTreeArray($v['pid']); $objList = array_merge($objList, Tree::instance()->getTreeList($obj)); } $childrenGroupIds = []; foreach ($objList as $k => $v) { $childrenGroupIds[] = $v['id']; } if (!$withself) { $childrenGroupIds = array_diff($childrenGroupIds, $groupIds); } return $childrenGroupIds; } /** * 取出当前管理员所拥有权限的管理员 * @param boolean $withself 是否包含自身 * @return array */ public function getChildrenAdminIds($withself = false) { $childrenAdminIds = []; if (!$this->isSuperAdmin()) { $groupIds = $this->getChildrenGroupIds(false); $authGroupList = \app\company\model\AuthGroupAccess::field('uid,group_id') ->where('group_id', 'in', $groupIds) ->select(); foreach ($authGroupList as $k => $v) { $childrenAdminIds[] = $v['uid']; } } else { //超级管理员拥有所有人的权限 // $childrenAdminIds = User::column('id'); $childrenAdminIds = User::where('company_id',$this->company_id)->column('id'); } if ($withself) { if (!in_array($this->id, $childrenAdminIds)) { $childrenAdminIds[] = $this->id; } } else { $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]); } return $childrenAdminIds; } /** * 获得面包屑导航 * @param string $path * @return array */ public function getBreadCrumb($path = '') { if ($this->breadcrumb || !$path) { return $this->breadcrumb; } $titleArr = []; $menuArr = []; $urlArr = explode('/', $path); foreach ($urlArr as $index => $item) { $pathArr[implode('/', array_slice($urlArr, 0, $index + 1))] = $index; } if (!$this->rules && $this->id) { $this->getRuleList(); } foreach ($this->rules as $rule) { if (isset($pathArr[$rule['name']])) { $rule['title'] = __($rule['title']); $rule['url'] = url($rule['name']); $titleArr[$pathArr[$rule['name']]] = $rule['title']; $menuArr[$pathArr[$rule['name']]] = $rule; } } ksort($menuArr); $this->breadcrumb = $menuArr; return $this->breadcrumb; } /** * 获取左侧菜单栏 * * @param array $params URL对应的badge数据 * @param string $fixedPage 默认页 * @return array */ public function get_menus(){ // 读取管理员当前拥有的权限节点 $userRule = $this->getRuleList(); // 必须将结果集转换为数组 $ruleList = collection(\app\admin\model\PcAuthRule::where('status', 'normal') ->field('id,pid as parentId,name as namerule,title as name,path,component,component_name as componentName,icon,visible,alwaysShow,keepAlive') ->where('type', 'NEQ',3) ->order('weigh', 'desc') ->select())->toArray(); foreach ($ruleList as $k => &$v) { $v['visible'] = $v['visible'] == 1 ? true : false; $v['alwaysShow'] = $v['alwaysShow'] == 1 ? true : false; $v['keepAlive'] = $v['keepAlive'] == 1 ? true : false; if (!in_array($v['namerule'], $userRule)) { unset($ruleList[$k]); continue; } //如果你不是客服,但是又有客服菜单权限,直接强行删掉 if($this->is_kefu == 0 && in_array($v['namerule'],['company/kefu','company/kefu/list']) ){ unset($ruleList[$k]); continue; } } // dump($ruleList); Tree::instance()->init($ruleList,'parentId'); $menu = Tree::instance()->getTreeArray_2(0); // dump($menu); return $menu; } public function get_menus_simple(){ // 读取管理员当前拥有的权限节点 $userRule = $this->getRuleList(); // 必须将结果集转换为数组 $ruleList = collection(\app\admin\model\PcAuthRule::where('status', 'normal') ->field('id,pid as parentId,name as namerule,title as name,path,component,component_name as componentName,icon,visible,alwaysShow,keepAlive') ->where('type',1)->where('pid',0) ->order('weigh', 'desc') ->select())->toArray(); foreach ($ruleList as $k => &$v) { $v['visible'] = $v['visible'] == 1 ? true : false; $v['alwaysShow'] = $v['alwaysShow'] == 1 ? true : false; $v['keepAlive'] = $v['keepAlive'] == 1 ? true : false; if (!in_array($v['namerule'], $userRule)) { unset($ruleList[$k]); continue; } //如果你不是客服,但是又有客服菜单权限,直接强行删掉 if($this->is_kefu == 0 && in_array($v['namerule'],['company/kefu','company/kefu/list']) ){ unset($ruleList[$k]); continue; } } // return $ruleList; // dump($ruleList); Tree::instance()->init($ruleList,'parentId'); $menu = Tree::instance()->getTreeArray_2(0); // dump($menu); return $menu; } public function get_permissions(){ // 读取管理员当前拥有的权限节点 $userRule = $this->getRuleList(); // 必须将结果集转换为数组 $ruleList = collection(\app\admin\model\PcAuthRule::where('status', 'normal') ->where('type', 3) ->order('weigh', 'desc') ->select())->toArray(); foreach ($ruleList as $k => &$v) { if (!in_array($v['name'], $userRule)) { unset($ruleList[$k]); continue; } } // dump($ruleList); return array_column($ruleList,'permission'); } /* public function getSidebar($params = [], $fixedPage = 'dashboard') { // 边栏开始 Hook::listen("admin_sidebar_begin", $params); $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple']; $colorNums = count($colorArr); $badgeList = []; $module = request()->module(); // 生成菜单的badge foreach ($params as $k => $v) { $url = $k; if (is_array($v)) { $nums = $v[0] ?? 0; $color = $v[1] ?? $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums]; $class = $v[2] ?? 'label'; } else { $nums = $v; $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums]; $class = 'label'; } //必须nums大于0才显示 if ($nums) { $badgeList[$url] = '' . $nums . ''; } } // 读取管理员当前拥有的权限节点 $userRule = $this->getRuleList(); $selected = $referer = []; $refererUrl = Session::get('referer'); // 必须将结果集转换为数组 $ruleList = collection(\app\admin\model\PcAuthRule::where('status', 'normal') ->where('ismenu', 1) ->order('weigh', 'desc') ->cache("__menu__") ->select())->toArray(); $indexRuleList = \app\admin\model\PcAuthRule::where('status', 'normal') ->where('ismenu', 0) ->where('name', 'like', '%/index') ->column('name,pid'); $pidArr = array_unique(array_filter(array_column($ruleList, 'pid'))); foreach ($ruleList as $k => &$v) { if (!in_array($v['name'], $userRule)) { unset($ruleList[$k]); continue; } $indexRuleName = $v['name'] . '/index'; if (isset($indexRuleList[$indexRuleName]) && !in_array($indexRuleName, $userRule)) { unset($ruleList[$k]); continue; } $v['icon'] = $v['icon'] . ' fa-fw'; $v['url'] = isset($v['url']) && $v['url'] ? $v['url'] : '/' . $module . '/' . $v['name']; $v['badge'] = $badgeList[$v['name']] ?? ''; $v['title'] = __($v['title']); $v['url'] = preg_match("/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i", $v['url']) ? $v['url'] : url($v['url']); $v['menuclass'] = in_array($v['menutype'], ['dialog', 'ajax']) ? 'btn-' . $v['menutype'] : ''; $v['menutabs'] = !$v['menutype'] || in_array($v['menutype'], ['default', 'addtabs']) ? 'addtabs="' . $v['id'] . '"' : ''; $selected = $v['name'] == $fixedPage ? $v : $selected; $referer = $v['url'] == $refererUrl ? $v : $referer; } $lastArr = array_unique(array_filter(array_column($ruleList, 'pid'))); $pidDiffArr = array_diff($pidArr, $lastArr); foreach ($ruleList as $index => $item) { if (in_array($item['id'], $pidDiffArr)) { unset($ruleList[$index]); } } if ($selected == $referer) { $referer = []; } $select_id = $referer ? $referer['id'] : ($selected ? $selected['id'] : 0); $menu = $nav = ''; $showSubmenu = config('fastadmin.show_submenu'); if (Config::get('fastadmin.multiplenav')) { $topList = []; foreach ($ruleList as $index => $item) { if (!$item['pid']) { $topList[] = $item; } } $selectParentIds = []; $tree = Tree::instance(); $tree->init($ruleList); if ($select_id) { $selectParentIds = $tree->getParentsIds($select_id, true); } foreach ($topList as $index => $item) { $childList = Tree::instance()->getTreeMenu( $item['id'], '
  • @title @caret @badge @childlist
  • ', $select_id, '', 'ul', 'class="treeview-menu' . ($showSubmenu ? ' menu-open' : '') . '"' ); $current = in_array($item['id'], $selectParentIds); $url = $childList ? 'javascript:;' : $item['url']; $addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=" . ($item['menutype'] ? $item['menutype'] : 'addtabs'); $childList = str_replace( '" pid="' . $item['id'] . '"', ' ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"', $childList ); $nav .= '
  • ' . $item['title'] . '
  • '; $menu .= $childList; } } else { // 构造菜单数据 Tree::instance()->init($ruleList); $menu = Tree::instance()->getTreeMenu( 0, '
  • @title @caret @badge @childlist
  • ', $select_id, '', 'ul', 'class="treeview-menu' . ($showSubmenu ? ' menu-open' : '') . '"' ); if ($selected) { $nav .= ''; } if ($referer) { $nav .= ''; } } return [$menu, $nav, $selected, $referer]; } */ /** * 获取允许输出的字段 * @return array */ public function getAllowFields() { return $this->allowFields; } /** * 设置允许输出的字段 * @param array $fields */ public function setAllowFields($fields) { $this->allowFields = $fields; } /** * 删除一个指定会员 * @param int $user_id 会员ID * @return boolean */ public function delete($user_id) { $user = User::get($user_id); if (!$user) { return false; } Db::startTrans(); try { // 删除会员 User::destroy($user_id); // 删除会员指定的所有Token Tokencompany::clear($user_id); Hook::listen("company_delete_successed", $user); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->setError($e->getMessage()); return false; } return true; } /** * 获取密码加密后的字符串 * @param string $password 密码 * @param string $salt 密码盐 * @return string */ public function getEncryptPassword($password, $salt = '') { return md5(md5($password) . $salt); } /** * 设置会话有效时间 * @param int $keeptime 默认为永久 */ public function keeptime($keeptime = 0) { $this->keeptime = $keeptime; } /** * 设置错误信息 * * @param string $error 错误信息 * @return Auth */ public function setError($error) { $this->_error = $error; return $this; } /** * 获取错误信息 * @return string */ public function getError() { return $this->_error ? __($this->_error) : ''; } }