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 ($admin->loginfailure >= 3 && 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. // 是否存在
  146. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr))
  147. {
  148. return TRUE;
  149. }
  150. // 没找到匹配
  151. return FALSE;
  152. }
  153. /**
  154. * 检测是否登录
  155. *
  156. * @return boolean
  157. */
  158. public function isLogin()
  159. {
  160. if ($this->logined)
  161. {
  162. return true;
  163. }
  164. $admin = Session::get('admin');
  165. if (!$admin)
  166. {
  167. return false;
  168. }
  169. //判断是否同一时间同一账号只能在一个地方登录
  170. if (Config::get('fastadmin.login_unique'))
  171. {
  172. $my = Admin::get($admin['id']);
  173. if (!$my || $my['token'] != $admin['token'])
  174. {
  175. return false;
  176. }
  177. }
  178. $this->logined = true;
  179. return true;
  180. }
  181. /**
  182. * 获取当前请求的URI
  183. * @return string
  184. */
  185. public function getRequestUri()
  186. {
  187. return $this->requestUri;
  188. }
  189. /**
  190. * 设置当前请求的URI
  191. * @param string $uri
  192. */
  193. public function setRequestUri($uri)
  194. {
  195. $this->requestUri = $uri;
  196. }
  197. public function getGroups($uid = null)
  198. {
  199. $uid = is_null($uid) ? $this->id : $uid;
  200. return parent::getGroups($uid);
  201. }
  202. public function getRuleList($uid = null)
  203. {
  204. $uid = is_null($uid) ? $this->id : $uid;
  205. return parent::getRuleList($uid);
  206. }
  207. public function getUserInfo($uid = null)
  208. {
  209. $uid = is_null($uid) ? $this->id : $uid;
  210. return $uid != $this->id ? Admin::get(intval($uid)) : Session::get('admin');
  211. }
  212. public function getRuleIds($uid = null)
  213. {
  214. $uid = is_null($uid) ? $this->id : $uid;
  215. return parent::getRuleIds($uid);
  216. }
  217. public function isSuperAdmin()
  218. {
  219. return in_array('*', $this->getRuleIds()) ? TRUE : FALSE;
  220. }
  221. /**
  222. * 获取管理员所属于的分组ID
  223. * @param int $uid
  224. * @return array
  225. */
  226. public function getGroupIds($uid = null)
  227. {
  228. $groups = $this->getGroups($uid);
  229. $groupIds = [];
  230. foreach ($groups as $K => $v)
  231. {
  232. $groupIds[] = (int) $v['group_id'];
  233. }
  234. return $groupIds;
  235. }
  236. /**
  237. * 取出当前管理员所拥有权限的分组
  238. * @param boolean $withself 是否包含当前所在的分组
  239. * @return array
  240. */
  241. public function getChildrenGroupIds($withself = false)
  242. {
  243. //取出当前管理员所有的分组
  244. $groups = $this->getGroups();
  245. $groupIds = [];
  246. foreach ($groups as $k => $v)
  247. {
  248. $groupIds[] = $v['id'];
  249. }
  250. // 取出所有分组
  251. $groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
  252. $objList = [];
  253. foreach ($groups as $K => $v)
  254. {
  255. if ($v['rules'] === '*')
  256. {
  257. $objList = $groupList;
  258. break;
  259. }
  260. // 取出包含自己的所有子节点
  261. $childrenList = Tree::instance()->init($groupList)->getChildren($v['id'], true);
  262. $obj = Tree::instance()->init($childrenList)->getTreeArray($v['pid']);
  263. $objList = array_merge($objList, Tree::instance()->getTreeList($obj));
  264. }
  265. $childrenGroupIds = [];
  266. foreach ($objList as $k => $v)
  267. {
  268. $childrenGroupIds[] = $v['id'];
  269. }
  270. if (!$withself)
  271. {
  272. $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
  273. }
  274. return $childrenGroupIds;
  275. }
  276. /**
  277. * 取出当前管理员所拥有权限的管理员
  278. * @param boolean $withself 是否包含自身
  279. * @return array
  280. */
  281. public function getChildrenAdminIds($withself = false)
  282. {
  283. $childrenAdminIds = [];
  284. if (!$this->isSuperAdmin())
  285. {
  286. $groupIds = $this->getChildrenGroupIds(false);
  287. $authGroupList = \app\admin\model\AuthGroupAccess::
  288. field('uid,group_id')
  289. ->where('group_id', 'in', $groupIds)
  290. ->select();
  291. foreach ($authGroupList as $k => $v)
  292. {
  293. $childrenAdminIds[] = $v['uid'];
  294. }
  295. }
  296. else
  297. {
  298. //超级管理员拥有所有人的权限
  299. $childrenAdminIds = Admin::column('id');
  300. }
  301. if ($withself)
  302. {
  303. if (!in_array($this->id, $childrenAdminIds))
  304. {
  305. $childrenAdminIds[] = $this->id;
  306. }
  307. }
  308. else
  309. {
  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. $path_rule_id = 0;
  324. foreach ($this->rules as $rule)
  325. {
  326. $path_rule_id = $rule['name'] == $path ? $rule['id'] : $path_rule_id;
  327. }
  328. if ($path_rule_id)
  329. {
  330. $this->breadcrumb = Tree::instance()->init($this->rules)->getParents($path_rule_id, true);
  331. foreach ($this->breadcrumb as $k => &$v)
  332. {
  333. $v['url'] = url($v['name']);
  334. $v['title'] = __($v['title']);
  335. }
  336. }
  337. return $this->breadcrumb;
  338. }
  339. /**
  340. * 获取左侧菜单栏
  341. *
  342. * @param array $params URL对应的badge数据
  343. * @return string
  344. */
  345. public function getSidebar($params = [], $fixedPage = 'dashboard')
  346. {
  347. $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
  348. $colorNums = count($colorArr);
  349. $badgeList = [];
  350. $module = request()->module();
  351. // 生成菜单的badge
  352. foreach ($params as $k => $v)
  353. {
  354. $url = $k;
  355. if (is_array($v))
  356. {
  357. $nums = isset($v[0]) ? $v[0] : 0;
  358. $color = isset($v[1]) ? $v[1] : $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  359. $class = isset($v[2]) ? $v[2] : 'label';
  360. }
  361. else
  362. {
  363. $nums = $v;
  364. $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  365. $class = 'label';
  366. }
  367. //必须nums大于0才显示
  368. if ($nums)
  369. {
  370. $badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
  371. }
  372. }
  373. // 读取管理员当前拥有的权限节点
  374. $userRule = $this->getRuleList();
  375. $select_id = 0;
  376. $pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
  377. // 必须将结果集转换为数组
  378. $ruleList = collection(\app\admin\model\AuthRule::where('status', 'normal')->where('ismenu', 1)->order('weigh', 'desc')->cache("__menu__")->select())->toArray();
  379. foreach ($ruleList as $k => &$v)
  380. {
  381. if (!in_array($v['name'], $userRule))
  382. {
  383. unset($ruleList[$k]);
  384. continue;
  385. }
  386. $select_id = $v['name'] == $fixedPage ? $v['id'] : $select_id;
  387. $v['url'] = '/' . $module . '/' . $v['name'];
  388. $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
  389. $v['py'] = $pinyin->abbr($v['title'], '');
  390. $v['pinyin'] = $pinyin->permalink($v['title'], '');
  391. $v['title'] = __($v['title']);
  392. }
  393. // 构造菜单数据
  394. Tree::instance()->init($ruleList);
  395. $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"');
  396. return $menu;
  397. }
  398. /**
  399. * 设置错误信息
  400. *
  401. * @param $error 错误信息
  402. */
  403. public function setError($error)
  404. {
  405. $this->_error = $error;
  406. return $this;
  407. }
  408. /**
  409. * 获取错误信息
  410. * @return string
  411. */
  412. public function getError()
  413. {
  414. return $this->_error ? __($this->_error) : '';
  415. }
  416. }