Auth.php 12 KB

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