Auth.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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\Request;
  9. use think\Session;
  10. class Auth extends \fast\Auth
  11. {
  12. protected $_error = '';
  13. protected $requestUri = '';
  14. protected $breadcrumb = [];
  15. protected $logined = false; //登录状态
  16. public function __construct()
  17. {
  18. parent::__construct();
  19. }
  20. public function __get($name)
  21. {
  22. return Session::get('admin.' . $name);
  23. }
  24. /**
  25. * 管理员登录
  26. *
  27. * @param string $username 用户名
  28. * @param string $password 密码
  29. * @param int $keeptime 有效时长
  30. * @return boolean
  31. */
  32. public function login($username, $password, $keeptime = 0)
  33. {
  34. $admin = Admin::get(['username' => $username]);
  35. if (!$admin) {
  36. $this->setError('Username is incorrect');
  37. return false;
  38. }
  39. if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
  40. $this->setError('Please try again after 1 day');
  41. return false;
  42. }
  43. if ($admin->password != md5(md5($password) . $admin->salt)) {
  44. $admin->loginfailure++;
  45. $admin->save();
  46. $this->setError('Password is incorrect');
  47. return false;
  48. }
  49. $admin->loginfailure = 0;
  50. $admin->logintime = time();
  51. $admin->token = Random::uuid();
  52. $admin->save();
  53. Session::set("admin", $admin->toArray());
  54. $this->keeplogin($keeptime);
  55. return true;
  56. }
  57. /**
  58. * 注销登录
  59. */
  60. public function logout()
  61. {
  62. $admin = Admin::get(intval($this->id));
  63. if (!$admin) {
  64. return true;
  65. }
  66. $admin->token = '';
  67. $admin->save();
  68. Session::delete("admin");
  69. Cookie::delete("keeplogin");
  70. return true;
  71. }
  72. /**
  73. * 自动登录
  74. * @return boolean
  75. */
  76. public function autologin()
  77. {
  78. $keeplogin = Cookie::get('keeplogin');
  79. if (!$keeplogin) {
  80. return false;
  81. }
  82. list($id, $keeptime, $expiretime, $key) = explode('|', $keeplogin);
  83. if ($id && $keeptime && $expiretime && $key && $expiretime > time()) {
  84. $admin = Admin::get($id);
  85. if (!$admin || !$admin->token) {
  86. return false;
  87. }
  88. //token有变更
  89. if ($key != md5(md5($id) . md5($keeptime) . md5($expiretime) . $admin->token)) {
  90. return false;
  91. }
  92. Session::set("admin", $admin->toArray());
  93. //刷新自动登录的时效
  94. $this->keeplogin($keeptime);
  95. return true;
  96. } else {
  97. return false;
  98. }
  99. }
  100. /**
  101. * 刷新保持登录的Cookie
  102. *
  103. * @param int $keeptime
  104. * @return boolean
  105. */
  106. protected function keeplogin($keeptime = 0)
  107. {
  108. if ($keeptime) {
  109. $expiretime = time() + $keeptime;
  110. $key = md5(md5($this->id) . md5($keeptime) . md5($expiretime) . $this->token);
  111. $data = [$this->id, $keeptime, $expiretime, $key];
  112. Cookie::set('keeplogin', implode('|', $data), 86400 * 30);
  113. return true;
  114. }
  115. return false;
  116. }
  117. public function check($name, $uid = '', $relation = 'or', $mode = 'url')
  118. {
  119. return parent::check($name, $this->id, $relation, $mode);
  120. }
  121. /**
  122. * 检测当前控制器和方法是否匹配传递的数组
  123. *
  124. * @param array $arr 需要验证权限的数组
  125. */
  126. public function match($arr = [])
  127. {
  128. $request = Request::instance();
  129. $arr = is_array($arr) ? $arr : explode(',', $arr);
  130. if (!$arr) {
  131. return FALSE;
  132. }
  133. $arr = array_map('strtolower', $arr);
  134. // 是否存在
  135. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  136. return TRUE;
  137. }
  138. // 没找到匹配
  139. return FALSE;
  140. }
  141. /**
  142. * 检测是否登录
  143. *
  144. * @return boolean
  145. */
  146. public function isLogin()
  147. {
  148. if ($this->logined) {
  149. return true;
  150. }
  151. $admin = Session::get('admin');
  152. if (!$admin) {
  153. return false;
  154. }
  155. //判断是否同一时间同一账号只能在一个地方登录
  156. if (Config::get('fastadmin.login_unique')) {
  157. $my = Admin::get($admin['id']);
  158. if (!$my || $my['token'] != $admin['token']) {
  159. return false;
  160. }
  161. }
  162. $this->logined = true;
  163. return true;
  164. }
  165. /**
  166. * 获取当前请求的URI
  167. * @return string
  168. */
  169. public function getRequestUri()
  170. {
  171. return $this->requestUri;
  172. }
  173. /**
  174. * 设置当前请求的URI
  175. * @param string $uri
  176. */
  177. public function setRequestUri($uri)
  178. {
  179. $this->requestUri = $uri;
  180. }
  181. public function getGroups($uid = null)
  182. {
  183. $uid = is_null($uid) ? $this->id : $uid;
  184. return parent::getGroups($uid);
  185. }
  186. public function getRuleList($uid = null)
  187. {
  188. $uid = is_null($uid) ? $this->id : $uid;
  189. return parent::getRuleList($uid);
  190. }
  191. public function getUserInfo($uid = null)
  192. {
  193. $uid = is_null($uid) ? $this->id : $uid;
  194. return $uid != $this->id ? Admin::get(intval($uid)) : Session::get('admin');
  195. }
  196. public function getRuleIds($uid = null)
  197. {
  198. $uid = is_null($uid) ? $this->id : $uid;
  199. return parent::getRuleIds($uid);
  200. }
  201. public function isSuperAdmin()
  202. {
  203. return in_array('*', $this->getRuleIds()) ? TRUE : FALSE;
  204. }
  205. /**
  206. * 获取管理员所属于的分组ID
  207. * @param int $uid
  208. * @return array
  209. */
  210. public function getGroupIds($uid = null)
  211. {
  212. $groups = $this->getGroups($uid);
  213. $groupIds = [];
  214. foreach ($groups as $K => $v) {
  215. $groupIds[] = (int)$v['group_id'];
  216. }
  217. return $groupIds;
  218. }
  219. /**
  220. * 取出当前管理员所拥有权限的分组
  221. * @param boolean $withself 是否包含当前所在的分组
  222. * @return array
  223. */
  224. public function getChildrenGroupIds($withself = false)
  225. {
  226. //取出当前管理员所有的分组
  227. $groups = $this->getGroups();
  228. $groupIds = [];
  229. foreach ($groups as $k => $v) {
  230. $groupIds[] = $v['id'];
  231. }
  232. // 取出所有分组
  233. $groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
  234. $objList = [];
  235. foreach ($groups as $K => $v) {
  236. if ($v['rules'] === '*') {
  237. $objList = $groupList;
  238. break;
  239. }
  240. // 取出包含自己的所有子节点
  241. $childrenList = Tree::instance()->init($groupList)->getChildren($v['id'], true);
  242. $obj = Tree::instance()->init($childrenList)->getTreeArray($v['pid']);
  243. $objList = array_merge($objList, Tree::instance()->getTreeList($obj));
  244. }
  245. $childrenGroupIds = [];
  246. foreach ($objList as $k => $v) {
  247. $childrenGroupIds[] = $v['id'];
  248. }
  249. if (!$withself) {
  250. $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
  251. }
  252. return $childrenGroupIds;
  253. }
  254. /**
  255. * 取出当前管理员所拥有权限的管理员
  256. * @param boolean $withself 是否包含自身
  257. * @return array
  258. */
  259. public function getChildrenAdminIds($withself = false)
  260. {
  261. $childrenAdminIds = [];
  262. if (!$this->isSuperAdmin()) {
  263. $groupIds = $this->getChildrenGroupIds(false);
  264. $authGroupList = \app\admin\model\AuthGroupAccess::
  265. field('uid,group_id')
  266. ->where('group_id', 'in', $groupIds)
  267. ->select();
  268. foreach ($authGroupList as $k => $v) {
  269. $childrenAdminIds[] = $v['uid'];
  270. }
  271. } else {
  272. //超级管理员拥有所有人的权限
  273. $childrenAdminIds = Admin::column('id');
  274. }
  275. if ($withself) {
  276. if (!in_array($this->id, $childrenAdminIds)) {
  277. $childrenAdminIds[] = $this->id;
  278. }
  279. } else {
  280. $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
  281. }
  282. return $childrenAdminIds;
  283. }
  284. /**
  285. * 获得面包屑导航
  286. * @param string $path
  287. * @return array
  288. */
  289. public function getBreadCrumb($path = '')
  290. {
  291. if ($this->breadcrumb || !$path)
  292. return $this->breadcrumb;
  293. $path_rule_id = 0;
  294. foreach ($this->rules as $rule) {
  295. $path_rule_id = $rule['name'] == $path ? $rule['id'] : $path_rule_id;
  296. }
  297. if ($path_rule_id) {
  298. $this->breadcrumb = Tree::instance()->init($this->rules)->getParents($path_rule_id, true);
  299. foreach ($this->breadcrumb as $k => &$v) {
  300. $v['url'] = url($v['name']);
  301. $v['title'] = __($v['title']);
  302. }
  303. }
  304. return $this->breadcrumb;
  305. }
  306. /**
  307. * 获取左侧和顶部菜单栏
  308. *
  309. * @param array $params URL对应的badge数据
  310. * @param string $fixedPage 默认页
  311. * @return array
  312. */
  313. public function getSidebar($params = [], $fixedPage = 'dashboard')
  314. {
  315. $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
  316. $colorNums = count($colorArr);
  317. $badgeList = [];
  318. $module = request()->module();
  319. // 生成菜单的badge
  320. foreach ($params as $k => $v) {
  321. $url = $k;
  322. if (is_array($v)) {
  323. $nums = isset($v[0]) ? $v[0] : 0;
  324. $color = isset($v[1]) ? $v[1] : $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  325. $class = isset($v[2]) ? $v[2] : 'label';
  326. } else {
  327. $nums = $v;
  328. $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  329. $class = 'label';
  330. }
  331. //必须nums大于0才显示
  332. if ($nums) {
  333. $badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
  334. }
  335. }
  336. // 读取管理员当前拥有的权限节点
  337. $userRule = $this->getRuleList();
  338. $select_id = 0;
  339. $pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
  340. // 必须将结果集转换为数组
  341. $ruleList = collection(\app\admin\model\AuthRule::where('status', 'normal')->where('ismenu', 1)->order('weigh', 'desc')->cache("__menu__")->select())->toArray();
  342. foreach ($ruleList as $k => &$v) {
  343. if (!in_array($v['name'], $userRule)) {
  344. unset($ruleList[$k]);
  345. continue;
  346. }
  347. $select_id = $v['name'] == $fixedPage ? $v['id'] : $select_id;
  348. $v['url'] = '/' . $module . '/' . $v['name'];
  349. $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
  350. $v['py'] = $pinyin->abbr($v['title'], '');
  351. $v['pinyin'] = $pinyin->permalink($v['title'], '');
  352. $v['title'] = __($v['title']);
  353. }
  354. $menu = $nav = '';
  355. if (Config::get('fastadmin.multiplenav')) {
  356. $topList = [];
  357. foreach ($ruleList as $index => $item) {
  358. if (!$item['pid']) {
  359. $topList[] = $item;
  360. }
  361. }
  362. $selectParentIds = [];
  363. $tree = Tree::instance();
  364. $tree->init($ruleList);
  365. if ($select_id) {
  366. $selectParentIds = $tree->getParentsIds($select_id, true);
  367. }
  368. foreach ($topList as $index => $item) {
  369. $childList = Tree::instance()->getTreeMenu($item['id'], '<li class="@class" pid="@pid"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>', $select_id, '', 'ul', 'class="treeview-menu"');
  370. $current = in_array($item['id'], $selectParentIds);
  371. $url = $childList ? 'javascript:;' : url($item['url']);
  372. $addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=addtabs";
  373. $childList = str_replace('" pid="' . $item['id'] . '"', ' treeview ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"', $childList);
  374. $nav .= '<li class="' . ($current ? 'active' : '') . '"><a href="' . $url . $addtabs . '" addtabs="' . $item['id'] . '" url="' . $url . '"><i class="' . $item['icon'] . '"></i> <span>' . $item['title'] . '</span> <span class="pull-right-container"> </span></a> </li>';
  375. $menu .= $childList;
  376. }
  377. } else {
  378. // 构造菜单数据
  379. Tree::instance()->init($ruleList);
  380. $menu = Tree::instance()->getTreeMenu(0, '<li class="@class"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>', $select_id, '', 'ul', 'class="treeview-menu"');
  381. }
  382. return [$menu, $nav];
  383. }
  384. /**
  385. * 设置错误信息
  386. *
  387. * @param $error 错误信息
  388. * @return Auth
  389. */
  390. public function setError($error)
  391. {
  392. $this->_error = $error;
  393. return $this;
  394. }
  395. /**
  396. * 获取错误信息
  397. * @return string
  398. */
  399. public function getError()
  400. {
  401. return $this->_error ? __($this->_error) : '';
  402. }
  403. }