Auth.php 18 KB

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