Auth.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 . config('token.key'))) {
  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 . config('token.key'));
  122. $data = [$this->id, $keeptime, $expiretime, $key];
  123. Cookie::set('keeplogin', implode('|', $data), 86400 * 7);
  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->logined = false; //重置登录状态
  173. Session::delete("admin");
  174. Cookie::delete("keeplogin");
  175. return false;
  176. }
  177. }
  178. //判断管理员IP是否变动
  179. if (Config::get('fastadmin.loginip_check')) {
  180. if (!isset($admin['loginip']) || $admin['loginip'] != request()->ip()) {
  181. $this->logout();
  182. return false;
  183. }
  184. }
  185. $this->logined = true;
  186. return true;
  187. }
  188. /**
  189. * 获取当前请求的URI
  190. * @return string
  191. */
  192. public function getRequestUri()
  193. {
  194. return $this->requestUri;
  195. }
  196. /**
  197. * 设置当前请求的URI
  198. * @param string $uri
  199. */
  200. public function setRequestUri($uri)
  201. {
  202. $this->requestUri = $uri;
  203. }
  204. public function getGroups($uid = null)
  205. {
  206. $uid = is_null($uid) ? $this->id : $uid;
  207. return parent::getGroups($uid);
  208. }
  209. public function getRuleList($uid = null)
  210. {
  211. $uid = is_null($uid) ? $this->id : $uid;
  212. return parent::getRuleList($uid);
  213. }
  214. public function getUserInfo($uid = null)
  215. {
  216. $uid = is_null($uid) ? $this->id : $uid;
  217. return $uid != $this->id ? Admin::get(intval($uid)) : Session::get('admin');
  218. }
  219. public function getRuleIds($uid = null)
  220. {
  221. $uid = is_null($uid) ? $this->id : $uid;
  222. return parent::getRuleIds($uid);
  223. }
  224. public function isSuperAdmin()
  225. {
  226. return in_array('*', $this->getRuleIds()) ? true : false;
  227. }
  228. /**
  229. * 获取管理员所属于的分组ID
  230. * @param int $uid
  231. * @return array
  232. */
  233. public function getGroupIds($uid = null)
  234. {
  235. $groups = $this->getGroups($uid);
  236. $groupIds = [];
  237. foreach ($groups as $K => $v) {
  238. $groupIds[] = (int)$v['group_id'];
  239. }
  240. return $groupIds;
  241. }
  242. /**
  243. * 取出当前管理员所拥有权限的分组
  244. * @param boolean $withself 是否包含当前所在的分组
  245. * @return array
  246. */
  247. public function getChildrenGroupIds($withself = false)
  248. {
  249. //取出当前管理员所有的分组
  250. $groups = $this->getGroups();
  251. $groupIds = [];
  252. foreach ($groups as $k => $v) {
  253. $groupIds[] = $v['id'];
  254. }
  255. $originGroupIds = $groupIds;
  256. foreach ($groups as $k => $v) {
  257. if (in_array($v['pid'], $originGroupIds)) {
  258. $groupIds = array_diff($groupIds, [$v['id']]);
  259. unset($groups[$k]);
  260. }
  261. }
  262. // 取出所有分组
  263. $groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
  264. $objList = [];
  265. foreach ($groups as $k => $v) {
  266. if ($v['rules'] === '*') {
  267. $objList = $groupList;
  268. break;
  269. }
  270. // 取出包含自己的所有子节点
  271. $childrenList = Tree::instance()->init($groupList, 'pid')->getChildren($v['id'], true);
  272. $obj = Tree::instance()->init($childrenList, 'pid')->getTreeArray($v['pid']);
  273. $objList = array_merge($objList, Tree::instance()->getTreeList($obj));
  274. }
  275. $childrenGroupIds = [];
  276. foreach ($objList as $k => $v) {
  277. $childrenGroupIds[] = $v['id'];
  278. }
  279. if (!$withself) {
  280. $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
  281. }
  282. return $childrenGroupIds;
  283. }
  284. /**
  285. * 取出当前管理员所拥有权限的管理员
  286. * @param boolean $withself 是否包含自身
  287. * @return array
  288. */
  289. public function getChildrenAdminIds($withself = false)
  290. {
  291. $childrenAdminIds = [];
  292. if (!$this->isSuperAdmin()) {
  293. $groupIds = $this->getChildrenGroupIds(false);
  294. $authGroupList = \app\admin\model\AuthGroupAccess::
  295. field('uid,group_id')
  296. ->where('group_id', 'in', $groupIds)
  297. ->select();
  298. foreach ($authGroupList as $k => $v) {
  299. $childrenAdminIds[] = $v['uid'];
  300. }
  301. } else {
  302. //超级管理员拥有所有人的权限
  303. $childrenAdminIds = Admin::column('id');
  304. }
  305. if ($withself) {
  306. if (!in_array($this->id, $childrenAdminIds)) {
  307. $childrenAdminIds[] = $this->id;
  308. }
  309. } else {
  310. $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
  311. }
  312. return $childrenAdminIds;
  313. }
  314. /**
  315. * 获得面包屑导航
  316. * @param string $path
  317. * @return array
  318. */
  319. public function getBreadCrumb($path = '')
  320. {
  321. if ($this->breadcrumb || !$path) {
  322. return $this->breadcrumb;
  323. }
  324. $titleArr = [];
  325. $menuArr = [];
  326. $urlArr = explode('/', $path);
  327. foreach ($urlArr as $index => $item) {
  328. $pathArr[implode('/', array_slice($urlArr, 0, $index + 1))] = $index;
  329. }
  330. if (!$this->rules && $this->id) {
  331. $this->getRuleList();
  332. }
  333. foreach ($this->rules as $rule) {
  334. if (isset($pathArr[$rule['name']])) {
  335. $rule['title'] = __($rule['title']);
  336. $rule['url'] = url($rule['name']);
  337. $titleArr[$pathArr[$rule['name']]] = $rule['title'];
  338. $menuArr[$pathArr[$rule['name']]] = $rule;
  339. }
  340. }
  341. ksort($menuArr);
  342. $this->breadcrumb = $menuArr;
  343. return $this->breadcrumb;
  344. }
  345. /**
  346. * 获取左侧和顶部菜单栏
  347. *
  348. * @param array $params URL对应的badge数据
  349. * @param string $fixedPage 默认页
  350. * @return array
  351. */
  352. public function getSidebar($params = [], $fixedPage = 'dashboard')
  353. {
  354. // 边栏开始
  355. Hook::listen("admin_sidebar_begin", $params);
  356. $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
  357. $colorNums = count($colorArr);
  358. $badgeList = [];
  359. $module = request()->module();
  360. // 生成菜单的badge
  361. foreach ($params as $k => $v) {
  362. $url = $k;
  363. if (is_array($v)) {
  364. $nums = isset($v[0]) ? $v[0] : 0;
  365. $color = isset($v[1]) ? $v[1] : $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  366. $class = isset($v[2]) ? $v[2] : 'label';
  367. } else {
  368. $nums = $v;
  369. $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  370. $class = 'label';
  371. }
  372. //必须nums大于0才显示
  373. if ($nums) {
  374. $badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
  375. }
  376. }
  377. // 读取管理员当前拥有的权限节点
  378. $userRule = $this->getRuleList();
  379. $selected = $referer = [];
  380. $refererUrl = Session::get('referer');
  381. // 必须将结果集转换为数组
  382. $ruleList = collection(\app\admin\model\AuthRule::where('status', 'normal')
  383. ->where('ismenu', 1)
  384. ->order('weigh', 'desc')
  385. ->cache("__menu__")
  386. ->select())->toArray();
  387. $indexRuleList = \app\admin\model\AuthRule::where('status', 'normal')
  388. ->where('ismenu', 0)
  389. ->where('name', 'like', '%/index')
  390. ->column('name,pid');
  391. $pidArr = array_unique(array_filter(array_column($ruleList, 'pid')));
  392. foreach ($ruleList as $k => &$v) {
  393. if (!in_array($v['name'], $userRule)) {
  394. unset($ruleList[$k]);
  395. continue;
  396. }
  397. $indexRuleName = $v['name'] . '/index';
  398. if (isset($indexRuleList[$indexRuleName]) && !in_array($indexRuleName, $userRule)) {
  399. unset($ruleList[$k]);
  400. continue;
  401. }
  402. $v['icon'] = $v['icon'] . ' fa-fw';
  403. $v['url'] = isset($v['url']) && $v['url'] ? $v['url'] : '/' . $module . '/' . $v['name'];
  404. $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
  405. $v['title'] = __($v['title']);
  406. $v['url'] = preg_match("/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i", $v['url']) ? $v['url'] : url($v['url']);
  407. $v['menuclass'] = in_array($v['menutype'], ['dialog', 'ajax']) ? 'btn-' . $v['menutype'] : '';
  408. $v['menutabs'] = !$v['menutype'] || in_array($v['menutype'], ['default', 'addtabs']) ? 'addtabs="' . $v['id'] . '"' : '';
  409. $selected = $v['name'] == $fixedPage ? $v : $selected;
  410. $referer = $v['url'] == $refererUrl ? $v : $referer;
  411. }
  412. $lastArr = array_unique(array_filter(array_column($ruleList, 'pid')));
  413. $pidDiffArr = array_diff($pidArr, $lastArr);
  414. foreach ($ruleList as $index => $item) {
  415. if (in_array($item['id'], $pidDiffArr)) {
  416. unset($ruleList[$index]);
  417. }
  418. }
  419. if ($selected == $referer) {
  420. $referer = [];
  421. }
  422. $select_id = $referer ? $referer['id'] : ($selected ? $selected['id'] : 0);
  423. $menu = $nav = '';
  424. $showSubmenu = config('fastadmin.show_submenu');
  425. if (Config::get('fastadmin.multiplenav')) {
  426. $topList = [];
  427. foreach ($ruleList as $index => $item) {
  428. if (!$item['pid']) {
  429. $topList[] = $item;
  430. }
  431. }
  432. $selectParentIds = [];
  433. $tree = Tree::instance();
  434. $tree->init($ruleList);
  435. if ($select_id) {
  436. $selectParentIds = $tree->getParentsIds($select_id, true);
  437. }
  438. foreach ($topList as $index => $item) {
  439. $childList = Tree::instance()->getTreeMenu(
  440. $item['id'],
  441. '<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>',
  442. $select_id,
  443. '',
  444. 'ul',
  445. 'class="treeview-menu' . ($showSubmenu ? ' menu-open' : '') . '"'
  446. );
  447. $current = in_array($item['id'], $selectParentIds);
  448. $url = $childList ? 'javascript:;' : $item['url'];
  449. $addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=addtabs";
  450. $childList = str_replace(
  451. '" pid="' . $item['id'] . '"',
  452. ' ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"',
  453. $childList
  454. );
  455. $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>';
  456. $menu .= $childList;
  457. }
  458. } else {
  459. // 构造菜单数据
  460. Tree::instance()->init($ruleList);
  461. $menu = Tree::instance()->getTreeMenu(
  462. 0,
  463. '<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>',
  464. $select_id,
  465. '',
  466. 'ul',
  467. 'class="treeview-menu' . ($showSubmenu ? ' menu-open' : '') . '"'
  468. );
  469. if ($selected) {
  470. $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>';
  471. }
  472. if ($referer) {
  473. $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>';
  474. }
  475. }
  476. return [$menu, $nav, $selected, $referer];
  477. }
  478. /**
  479. * 设置错误信息
  480. *
  481. * @param string $error 错误信息
  482. * @return Auth
  483. */
  484. public function setError($error)
  485. {
  486. $this->_error = $error;
  487. return $this;
  488. }
  489. /**
  490. * 获取错误信息
  491. * @return string
  492. */
  493. public function getError()
  494. {
  495. return $this->_error ? __($this->_error) : '';
  496. }
  497. }