You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

533 lines
17 KiB

  1. <?php
  2. namespace app\admin\library;
  3. use app\admin\model\Admin;
  4. use fast\Random;
  5. use fast\Tree;
  6. use think\Config;
  7. use think\Cookie;
  8. use think\Hook;
  9. use think\Request;
  10. use think\Session;
  11. class Auth extends \fast\Auth
  12. {
  13. protected $_error = '';
  14. protected $requestUri = '';
  15. protected $breadcrumb = [];
  16. protected $logined = false; //登录状态
  17. public function __construct()
  18. {
  19. parent::__construct();
  20. }
  21. public function __get($name)
  22. {
  23. return Session::get('admin.' . $name);
  24. }
  25. /**
  26. * 管理员登录
  27. *
  28. * @param string $username 用户名
  29. * @param string $password 密码
  30. * @param int $keeptime 有效时长
  31. * @return boolean
  32. */
  33. public function login($username, $password, $keeptime = 0)
  34. {
  35. $admin = Admin::get(['username' => $username]);
  36. if (!$admin) {
  37. $this->setError('Username is incorrect');
  38. return false;
  39. }
  40. if ($admin['status'] == 'hidden') {
  41. $this->setError('Admin is forbidden');
  42. return false;
  43. }
  44. if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
  45. $this->setError('Please try again after 1 day');
  46. return false;
  47. }
  48. if ($admin->password != md5(md5($password) . $admin->salt)) {
  49. $admin->loginfailure++;
  50. $admin->save();
  51. $this->setError('Password is incorrect');
  52. return false;
  53. }
  54. $admin->loginfailure = 0;
  55. $admin->logintime = time();
  56. $admin->loginip = request()->ip();
  57. $admin->token = Random::uuid();
  58. $admin->save();
  59. Session::set("admin", $admin->toArray());
  60. $this->keeplogin($keeptime);
  61. return true;
  62. }
  63. /**
  64. * 注销登录
  65. */
  66. public function logout()
  67. {
  68. $admin = Admin::get(intval($this->id));
  69. if ($admin) {
  70. $admin->token = '';
  71. $admin->save();
  72. }
  73. $this->logined = false; //重置登录状态
  74. Session::delete("admin");
  75. Cookie::delete("keeplogin");
  76. return true;
  77. }
  78. /**
  79. * 自动登录
  80. * @return boolean
  81. */
  82. public function autologin()
  83. {
  84. $keeplogin = Cookie::get('keeplogin');
  85. if (!$keeplogin) {
  86. return false;
  87. }
  88. list($id, $keeptime, $expiretime, $key) = explode('|', $keeplogin);
  89. if ($id && $keeptime && $expiretime && $key && $expiretime > time()) {
  90. $admin = Admin::get($id);
  91. if (!$admin || !$admin->token) {
  92. return false;
  93. }
  94. //token有变更
  95. if ($key != md5(md5($id) . md5($keeptime) . md5($expiretime) . $admin->token)) {
  96. return false;
  97. }
  98. $ip = request()->ip();
  99. //IP有变动
  100. if ($admin->loginip != $ip) {
  101. return false;
  102. }
  103. Session::set("admin", $admin->toArray());
  104. //刷新自动登录的时效
  105. $this->keeplogin($keeptime);
  106. return true;
  107. } else {
  108. return false;
  109. }
  110. }
  111. /**
  112. * 刷新保持登录的Cookie
  113. *
  114. * @param int $keeptime
  115. * @return boolean
  116. */
  117. protected function keeplogin($keeptime = 0)
  118. {
  119. if ($keeptime) {
  120. $expiretime = time() + $keeptime;
  121. $key = md5(md5($this->id) . md5($keeptime) . md5($expiretime) . $this->token);
  122. $data = [$this->id, $keeptime, $expiretime, $key];
  123. Cookie::set('keeplogin', implode('|', $data), 86400 * 30);
  124. return true;
  125. }
  126. return false;
  127. }
  128. public function check($name, $uid = '', $relation = 'or', $mode = 'url')
  129. {
  130. $uid = $uid ? $uid : $this->id;
  131. return parent::check($name, $uid, $relation, $mode);
  132. }
  133. /**
  134. * 检测当前控制器和方法是否匹配传递的数组
  135. *
  136. * @param array $arr 需要验证权限的数组
  137. * @return bool
  138. */
  139. public function match($arr = [])
  140. {
  141. $request = Request::instance();
  142. $arr = is_array($arr) ? $arr : explode(',', $arr);
  143. if (!$arr) {
  144. return false;
  145. }
  146. $arr = array_map('strtolower', $arr);
  147. // 是否存在
  148. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  149. return true;
  150. }
  151. // 没找到匹配
  152. return false;
  153. }
  154. /**
  155. * 检测是否登录
  156. *
  157. * @return boolean
  158. */
  159. public function isLogin()
  160. {
  161. if ($this->logined) {
  162. return true;
  163. }
  164. $admin = Session::get('admin');
  165. if (!$admin) {
  166. return false;
  167. }
  168. //判断是否同一时间同一账号只能在一个地方登录
  169. if (Config::get('fastadmin.login_unique')) {
  170. $my = Admin::get($admin['id']);
  171. if (!$my || $my['token'] != $admin['token']) {
  172. $this->logout();
  173. return false;
  174. }
  175. }
  176. //判断管理员IP是否变动
  177. if (Config::get('fastadmin.loginip_check')) {
  178. if (!isset($admin['loginip']) || $admin['loginip'] != request()->ip()) {
  179. $this->logout();
  180. return false;
  181. }
  182. }
  183. $this->logined = true;
  184. return true;
  185. }
  186. /**
  187. * 获取当前请求的URI
  188. * @return string
  189. */
  190. public function getRequestUri()
  191. {
  192. return $this->requestUri;
  193. }
  194. /**
  195. * 设置当前请求的URI
  196. * @param string $uri
  197. */
  198. public function setRequestUri($uri)
  199. {
  200. $this->requestUri = $uri;
  201. }
  202. public function getGroups($uid = null)
  203. {
  204. $uid = is_null($uid) ? $this->id : $uid;
  205. return parent::getGroups($uid);
  206. }
  207. public function getRuleList($uid = null)
  208. {
  209. $uid = is_null($uid) ? $this->id : $uid;
  210. return parent::getRuleList($uid);
  211. }
  212. public function getUserInfo($uid = null)
  213. {
  214. $uid = is_null($uid) ? $this->id : $uid;
  215. return $uid != $this->id ? Admin::get(intval($uid)) : Session::get('admin');
  216. }
  217. public function getRuleIds($uid = null)
  218. {
  219. $uid = is_null($uid) ? $this->id : $uid;
  220. return parent::getRuleIds($uid);
  221. }
  222. public function isSuperAdmin()
  223. {
  224. return in_array('*', $this->getRuleIds()) ? true : false;
  225. }
  226. /**
  227. * 获取管理员所属于的分组ID
  228. * @param int $uid
  229. * @return array
  230. */
  231. public function getGroupIds($uid = null)
  232. {
  233. $groups = $this->getGroups($uid);
  234. $groupIds = [];
  235. foreach ($groups as $K => $v) {
  236. $groupIds[] = (int)$v['group_id'];
  237. }
  238. return $groupIds;
  239. }
  240. /**
  241. * 取出当前管理员所拥有权限的分组
  242. * @param boolean $withself 是否包含当前所在的分组
  243. * @return array
  244. */
  245. public function getChildrenGroupIds($withself = false)
  246. {
  247. //取出当前管理员所有的分组
  248. $groups = $this->getGroups();
  249. $groupIds = [];
  250. foreach ($groups as $k => $v) {
  251. $groupIds[] = $v['id'];
  252. }
  253. $originGroupIds = $groupIds;
  254. foreach ($groups as $k => $v) {
  255. if (in_array($v['pid'], $originGroupIds)) {
  256. $groupIds = array_diff($groupIds, [$v['id']]);
  257. unset($groups[$k]);
  258. }
  259. }
  260. // 取出所有分组
  261. $groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
  262. $objList = [];
  263. foreach ($groups as $k => $v) {
  264. if ($v['rules'] === '*') {
  265. $objList = $groupList;
  266. break;
  267. }
  268. // 取出包含自己的所有子节点
  269. $childrenList = Tree::instance()->init($groupList)->getChildren($v['id'], true);
  270. $obj = Tree::instance()->init($childrenList)->getTreeArray($v['pid']);
  271. $objList = array_merge($objList, Tree::instance()->getTreeList($obj));
  272. }
  273. $childrenGroupIds = [];
  274. foreach ($objList as $k => $v) {
  275. $childrenGroupIds[] = $v['id'];
  276. }
  277. if (!$withself) {
  278. $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
  279. }
  280. return $childrenGroupIds;
  281. }
  282. /**
  283. * 取出当前管理员所拥有权限的管理员
  284. * @param boolean $withself 是否包含自身
  285. * @return array
  286. */
  287. public function getChildrenAdminIds($withself = false)
  288. {
  289. $childrenAdminIds = [];
  290. if (!$this->isSuperAdmin()) {
  291. $groupIds = $this->getChildrenGroupIds(false);
  292. $authGroupList = \app\admin\model\AuthGroupAccess::
  293. field('uid,group_id')
  294. ->where('group_id', 'in', $groupIds)
  295. ->select();
  296. foreach ($authGroupList as $k => $v) {
  297. $childrenAdminIds[] = $v['uid'];
  298. }
  299. } else {
  300. //超级管理员拥有所有人的权限
  301. $childrenAdminIds = Admin::column('id');
  302. }
  303. if ($withself) {
  304. if (!in_array($this->id, $childrenAdminIds)) {
  305. $childrenAdminIds[] = $this->id;
  306. }
  307. } else {
  308. $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
  309. }
  310. return $childrenAdminIds;
  311. }
  312. /**
  313. * 获得面包屑导航
  314. * @param string $path
  315. * @return array
  316. */
  317. public function getBreadCrumb($path = '')
  318. {
  319. if ($this->breadcrumb || !$path) {
  320. return $this->breadcrumb;
  321. }
  322. $titleArr = [];
  323. $menuArr = [];
  324. $urlArr = explode('/', $path);
  325. foreach ($urlArr as $index => $item) {
  326. $pathArr[implode('/', array_slice($urlArr, 0, $index + 1))] = $index;
  327. }
  328. if (!$this->rules && $this->id) {
  329. $this->getRuleList();
  330. }
  331. foreach ($this->rules as $rule) {
  332. if (isset($pathArr[$rule['name']])) {
  333. $rule['title'] = __($rule['title']);
  334. $rule['url'] = url($rule['name']);
  335. $titleArr[$pathArr[$rule['name']]] = $rule['title'];
  336. $menuArr[$pathArr[$rule['name']]] = $rule;
  337. }
  338. }
  339. ksort($menuArr);
  340. $this->breadcrumb = $menuArr;
  341. return $this->breadcrumb;
  342. }
  343. /**
  344. * 获取左侧和顶部菜单栏
  345. *
  346. * @param array $params URL对应的badge数据
  347. * @param string $fixedPage 默认页
  348. * @return array
  349. */
  350. public function getSidebar($params = [], $fixedPage = 'dashboard')
  351. {
  352. // 边栏开始
  353. Hook::listen("admin_sidebar_begin", $params);
  354. $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
  355. $colorNums = count($colorArr);
  356. $badgeList = [];
  357. $module = request()->module();
  358. // 生成菜单的badge
  359. foreach ($params as $k => $v) {
  360. $url = $k;
  361. if (is_array($v)) {
  362. $nums = isset($v[0]) ? $v[0] : 0;
  363. $color = isset($v[1]) ? $v[1] : $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  364. $class = isset($v[2]) ? $v[2] : 'label';
  365. } else {
  366. $nums = $v;
  367. $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  368. $class = 'label';
  369. }
  370. //必须nums大于0才显示
  371. if ($nums) {
  372. $badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
  373. }
  374. }
  375. // 读取管理员当前拥有的权限节点
  376. $userRule = $this->getRuleList();
  377. $selected = $referer = [];
  378. $refererUrl = Session::get('referer');
  379. $pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
  380. // 必须将结果集转换为数组
  381. $ruleList = collection(\app\admin\model\AuthRule::where('status', 'normal')
  382. ->where('ismenu', 1)
  383. ->order('weigh', 'desc')
  384. ->cache("__menu__")
  385. ->select())->toArray();
  386. $indexRuleList = \app\admin\model\AuthRule::where('status', 'normal')
  387. ->where('ismenu', 0)
  388. ->where('name', 'like', '%/index')
  389. ->column('name,pid');
  390. $pidArr = array_filter(array_unique(array_map(function ($item) {
  391. return $item['pid'];
  392. }, $ruleList)));
  393. foreach ($ruleList as $k => &$v) {
  394. if (!in_array($v['name'], $userRule)) {
  395. unset($ruleList[$k]);
  396. continue;
  397. }
  398. $indexRuleName = $v['name'] . '/index';
  399. if (isset($indexRuleList[$indexRuleName]) && !in_array($indexRuleName, $userRule)) {
  400. unset($ruleList[$k]);
  401. continue;
  402. }
  403. $v['icon'] = $v['icon'] . ' fa-fw';
  404. $v['url'] = '/' . $module . '/' . $v['name'];
  405. $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
  406. $v['py'] = $pinyin->abbr($v['title'], '');
  407. $v['pinyin'] = $pinyin->permalink($v['title'], '');
  408. $v['title'] = __($v['title']);
  409. $selected = $v['name'] == $fixedPage ? $v : $selected;
  410. $referer = url($v['url']) == $refererUrl ? $v : $referer;
  411. }
  412. $lastArr = array_diff($pidArr, array_filter(array_unique(array_map(function ($item) {
  413. return $item['pid'];
  414. }, $ruleList))));
  415. foreach ($ruleList as $index => $item) {
  416. if (in_array($item['id'], $lastArr)) {
  417. unset($ruleList[$index]);
  418. }
  419. }
  420. if ($selected == $referer) {
  421. $referer = [];
  422. }
  423. $selected && $selected['url'] = url($selected['url']);
  424. $referer && $referer['url'] = url($referer['url']);
  425. $select_id = $selected ? $selected['id'] : 0;
  426. $menu = $nav = '';
  427. if (Config::get('fastadmin.multiplenav')) {
  428. $topList = [];
  429. foreach ($ruleList as $index => $item) {
  430. if (!$item['pid']) {
  431. $topList[] = $item;
  432. }
  433. }
  434. $selectParentIds = [];
  435. $tree = Tree::instance();
  436. $tree->init($ruleList);
  437. if ($select_id) {
  438. $selectParentIds = $tree->getParentsIds($select_id, true);
  439. }
  440. foreach ($topList as $index => $item) {
  441. $childList = Tree::instance()->getTreeMenu(
  442. $item['id'],
  443. '<li class="@class" pid="@pid"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>',
  444. $select_id,
  445. '',
  446. 'ul',
  447. 'class="treeview-menu"'
  448. );
  449. $current = in_array($item['id'], $selectParentIds);
  450. $url = $childList ? 'javascript:;' : url($item['url']);
  451. $addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=addtabs";
  452. $childList = str_replace(
  453. '" pid="' . $item['id'] . '"',
  454. ' treeview ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"',
  455. $childList
  456. );
  457. $nav .= '<li class="' . ($current ? 'active' : '') . '"><a href="' . $url . $addtabs . '" addtabs="' . $item['id'] . '" url="' . $url . '"><i class="' . $item['icon'] . '"></i> <span>' . $item['title'] . '</span> <span class="pull-right-container"> </span></a> </li>';
  458. $menu .= $childList;
  459. }
  460. } else {
  461. // 构造菜单数据
  462. Tree::instance()->init($ruleList);
  463. $menu = Tree::instance()->getTreeMenu(
  464. 0,
  465. '<li class="@class"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>',
  466. $select_id,
  467. '',
  468. 'ul',
  469. 'class="treeview-menu"'
  470. );
  471. if ($selected) {
  472. $nav .= '<li role="presentation" id="tab_' . $selected['id'] . '" class="' . ($referer ? '' : 'active') . '"><a href="#con_' . $selected['id'] . '" node-id="' . $selected['id'] . '" aria-controls="' . $selected['id'] . '" role="tab" data-toggle="tab"><i class="' . $selected['icon'] . ' fa-fw"></i> <span>' . $selected['title'] . '</span> </a></li>';
  473. }
  474. if ($referer) {
  475. $nav .= '<li role="presentation" id="tab_' . $referer['id'] . '" class="active"><a href="#con_' . $referer['id'] . '" node-id="' . $referer['id'] . '" aria-controls="' . $referer['id'] . '" role="tab" data-toggle="tab"><i class="' . $referer['icon'] . ' fa-fw"></i> <span>' . $referer['title'] . '</span> </a> <i class="close-tab fa fa-remove"></i></li>';
  476. }
  477. }
  478. return [$menu, $nav, $selected, $referer];
  479. }
  480. /**
  481. * 设置错误信息
  482. *
  483. * @param string $error 错误信息
  484. * @return Auth
  485. */
  486. public function setError($error)
  487. {
  488. $this->_error = $error;
  489. return $this;
  490. }
  491. /**
  492. * 获取错误信息
  493. * @return string
  494. */
  495. public function getError()
  496. {
  497. return $this->_error ? __($this->_error) : '';
  498. }
  499. }