酒店预订平台
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

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