Auth.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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(['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::
  346. field('uid,group_id')
  347. ->where('group_id', 'in', $groupIds)
  348. ->select();
  349. foreach ($authGroupList as $k => $v) {
  350. $childrenAdminIds[] = $v['uid'];
  351. }
  352. } else {
  353. //超级管理员拥有所有人的权限
  354. $childrenAdminIds = Admin::column('id');
  355. }
  356. if ($withself) {
  357. if (!in_array($this->id, $childrenAdminIds)) {
  358. $childrenAdminIds[] = $this->id;
  359. }
  360. } else {
  361. $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
  362. }
  363. return $childrenAdminIds;
  364. }
  365. /**
  366. * 获得面包屑导航
  367. * @param string $path
  368. * @return array
  369. */
  370. public function getBreadCrumb($path = '')
  371. {
  372. if ($this->breadcrumb || !$path) {
  373. return $this->breadcrumb;
  374. }
  375. $titleArr = [];
  376. $menuArr = [];
  377. $urlArr = explode('/', $path);
  378. foreach ($urlArr as $index => $item) {
  379. $pathArr[implode('/', array_slice($urlArr, 0, $index + 1))] = $index;
  380. }
  381. if (!$this->rules && $this->id) {
  382. $this->getRuleList();
  383. }
  384. foreach ($this->rules as $rule) {
  385. if (isset($pathArr[$rule['name']])) {
  386. $rule['title'] = __($rule['title']);
  387. $rule['url'] = url($rule['name']);
  388. $titleArr[$pathArr[$rule['name']]] = $rule['title'];
  389. $menuArr[$pathArr[$rule['name']]] = $rule;
  390. }
  391. }
  392. ksort($menuArr);
  393. $this->breadcrumb = $menuArr;
  394. return $this->breadcrumb;
  395. }
  396. /**
  397. * 获取左侧和顶部菜单栏
  398. *
  399. * @param array $params URL对应的badge数据
  400. * @param string $fixedPage 默认页
  401. * @return array
  402. */
  403. public function getSidebar($params = [], $fixedPage = 'dashboard')
  404. {
  405. // 边栏开始
  406. Hook::listen("admin_sidebar_begin", $params);
  407. $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
  408. $colorNums = count($colorArr);
  409. $badgeList = [];
  410. $module = request()->module();
  411. // 生成菜单的badge
  412. foreach ($params as $k => $v) {
  413. $url = $k;
  414. if (is_array($v)) {
  415. $nums = isset($v[0]) ? $v[0] : 0;
  416. $color = isset($v[1]) ? $v[1] : $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  417. $class = isset($v[2]) ? $v[2] : 'label';
  418. } else {
  419. $nums = $v;
  420. $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  421. $class = 'label';
  422. }
  423. //必须nums大于0才显示
  424. if ($nums) {
  425. $badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
  426. }
  427. }
  428. // 读取管理员当前拥有的权限节点
  429. $userRule = $this->getRuleList();
  430. $selected = $referer = [];
  431. $refererUrl = Session::get('referer');
  432. // 必须将结果集转换为数组
  433. $ruleList = collection(\app\admin\model\AuthRule::where('status', 'normal')
  434. ->where('ismenu', 2)
  435. ->order('weigh', 'desc')
  436. ->cache("__menu__")
  437. ->select())->toArray();
  438. $indexRuleList = \app\admin\model\AuthRule::where('status', 'normal')
  439. ->where('ismenu', 0)
  440. ->where('name', 'like', '%/index')
  441. ->column('name,pid');
  442. $pidArr = array_unique(array_filter(array_column($ruleList, 'pid')));
  443. foreach ($ruleList as $k => &$v) {
  444. if (!in_array($v['name'], $userRule)) {
  445. unset($ruleList[$k]);
  446. continue;
  447. }
  448. $indexRuleName = $v['name'] . '/index';
  449. if (isset($indexRuleList[$indexRuleName]) && !in_array($indexRuleName, $userRule)) {
  450. unset($ruleList[$k]);
  451. continue;
  452. }
  453. $v['icon'] = $v['icon'] . ' fa-fw';
  454. $v['url'] = isset($v['url']) && $v['url'] ? $v['url'] : '/' . $module . '/' . $v['name'];
  455. $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
  456. $v['title'] = __($v['title']);
  457. $v['url'] = preg_match("/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i", $v['url']) ? $v['url'] : url($v['url']);
  458. $v['menuclass'] = in_array($v['menutype'], ['dialog', 'ajax']) ? 'btn-' . $v['menutype'] : '';
  459. $v['menutabs'] = !$v['menutype'] || in_array($v['menutype'], ['default', 'addtabs']) ? 'addtabs="' . $v['id'] . '"' : '';
  460. $selected = $v['name'] == $fixedPage ? $v : $selected;
  461. $referer = $v['url'] == $refererUrl ? $v : $referer;
  462. }
  463. $lastArr = array_unique(array_filter(array_column($ruleList, 'pid')));
  464. $pidDiffArr = array_diff($pidArr, $lastArr);
  465. foreach ($ruleList as $index => $item) {
  466. if (in_array($item['id'], $pidDiffArr)) {
  467. unset($ruleList[$index]);
  468. }
  469. }
  470. if ($selected == $referer) {
  471. $referer = [];
  472. }
  473. $select_id = $referer ? $referer['id'] : ($selected ? $selected['id'] : 0);
  474. $menu = $nav = '';
  475. $showSubmenu = config('fastadmin.show_submenu');
  476. if (Config::get('fastadmin.multiplenav')) {
  477. $topList = [];
  478. foreach ($ruleList as $index => $item) {
  479. if (!$item['pid']) {
  480. $topList[] = $item;
  481. }
  482. }
  483. $selectParentIds = [];
  484. $tree = Tree::instance();
  485. $tree->init($ruleList);
  486. if ($select_id) {
  487. $selectParentIds = $tree->getParentsIds($select_id, true);
  488. }
  489. foreach ($topList as $index => $item) {
  490. $childList = Tree::instance()->getTreeMenu(
  491. $item['id'],
  492. '<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>',
  493. $select_id,
  494. '',
  495. 'ul',
  496. 'class="treeview-menu' . ($showSubmenu ? ' menu-open' : '') . '"'
  497. );
  498. $current = in_array($item['id'], $selectParentIds);
  499. $url = $childList ? 'javascript:;' : $item['url'];
  500. $addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=" . ($item['menutype'] ? $item['menutype'] : 'addtabs');
  501. $childList = str_replace(
  502. '" pid="' . $item['id'] . '"',
  503. ' ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"',
  504. $childList
  505. );
  506. $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>';
  507. $menu .= $childList;
  508. }
  509. } else {
  510. // 构造菜单数据
  511. Tree::instance()->init($ruleList);
  512. $menu = Tree::instance()->getTreeMenu(
  513. 0,
  514. '<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>',
  515. $select_id,
  516. '',
  517. 'ul',
  518. 'class="treeview-menu' . ($showSubmenu ? ' menu-open' : '') . '"'
  519. );
  520. if ($selected) {
  521. $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>';
  522. }
  523. if ($referer) {
  524. $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>';
  525. }
  526. }
  527. return [$menu, $nav, $selected, $referer];
  528. }
  529. /**
  530. * 设置错误信息
  531. *
  532. * @param string $error 错误信息
  533. * @return Auth
  534. */
  535. public function setError($error)
  536. {
  537. $this->_error = $error;
  538. return $this;
  539. }
  540. /**
  541. * 获取错误信息
  542. * @return string
  543. */
  544. public function getError()
  545. {
  546. return $this->_error ? __($this->_error) : '';
  547. }
  548. }