Auth.php 12 KB

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