Auth.php 20 KB

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