Auth.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // | Original reference: https://gitee.com/karson/fastadmin
  12. // +----------------------------------------------------------------------
  13. // +----------------------------------------------------------------------
  14. // | 后台用户服务
  15. // +----------------------------------------------------------------------
  16. namespace app\admin\library;
  17. use app\admin\model\AdminUser;
  18. use think\facade\Config;
  19. use think\facade\Cookie;
  20. use think\facade\Event;
  21. use think\facade\Request;
  22. use think\facade\Session;
  23. use util\Random;
  24. use util\Tree;
  25. class Auth extends \libs\Auth
  26. {
  27. //当前登录会员详细信息
  28. protected $error = '';
  29. protected $requestUri = '';
  30. protected bool $logined = false; //登录状态
  31. public function __construct()
  32. {
  33. parent::__construct();
  34. }
  35. public function __get($name)
  36. {
  37. return Session::get('admin.' . $name);
  38. }
  39. /**
  40. * 取出当前管理员所拥有权限的分组.
  41. * @param bool $withself 是否包含当前所在的分组
  42. * @return array
  43. * @throws \think\db\exception\DataNotFoundException
  44. * @throws \think\db\exception\DbException
  45. * @throws \think\db\exception\ModelNotFoundException
  46. */
  47. public function getChildrenGroupIds(bool $withself = false)
  48. {
  49. //取出当前管理员所有的分组
  50. $groups = $this->getGroups();
  51. $groupIds = array_column($groups, 'id');
  52. $originGroupIds = $groupIds;
  53. foreach ($groups as $k => $v) {
  54. if (in_array($v['parentid'], $originGroupIds)) {
  55. $groupIds = array_diff($groupIds, [$v['id']]);
  56. unset($groups[$k]);
  57. }
  58. }
  59. // 取出所有分组
  60. $groupList = \app\admin\model\AuthGroup::where('status', 1)->select()->toArray();
  61. $objList = [];
  62. foreach ($groups as $k => $v) {
  63. if ($v['rules'] === '*') {
  64. $objList = $groupList;
  65. break;
  66. }
  67. // 取出包含自己的所有子节点
  68. $childrenList = Tree::instance()->init($groupList)->getChildren($v['id'], true);
  69. $obj = Tree::instance()->init($childrenList)->getTreeArray($v['parentid']);
  70. $objList = array_merge($objList, Tree::instance()->getTreeList($obj, 'title'));
  71. }
  72. $childrenGroupIds = array_column($objList, 'id');
  73. if (!$withself) {
  74. $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
  75. }
  76. return $childrenGroupIds;
  77. }
  78. public function check($name, $uid = '', $mode = 'url', $relation = 'or'): bool
  79. {
  80. $uid = $uid ?: $this->id;
  81. return parent::check($name, $uid, $mode, $relation);
  82. }
  83. /**
  84. * 取出当前管理员所拥有权限的管理员.
  85. * @param bool $withself 是否包含自身
  86. * @return array
  87. * @throws \think\db\exception\DataNotFoundException
  88. * @throws \think\db\exception\DbException
  89. * @throws \think\db\exception\ModelNotFoundException
  90. */
  91. public function getChildrenAdminIds(bool $withself = false)
  92. {
  93. $childrenAdminIds = [];
  94. if (!$this->isAdministrator()) {
  95. $groupIds = $this->getChildrenGroupIds(false);
  96. $childrenAdminIds = \app\admin\model\AuthGroupAccess::where('group_id', 'in', $groupIds)->column('uid');
  97. } else {
  98. //超级管理员拥有所有人的权限
  99. $childrenAdminIds = AdminUser::column('id');
  100. }
  101. if ($withself) {
  102. if (!in_array($this->id, $childrenAdminIds)) {
  103. $childrenAdminIds[] = $this->id;
  104. }
  105. } else {
  106. $childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
  107. }
  108. return $childrenAdminIds;
  109. }
  110. /**
  111. * 获取当前请求的URI
  112. * @return string
  113. */
  114. public function getRequestUri()
  115. {
  116. return $this->requestUri;
  117. }
  118. /**
  119. * 设置当前请求的URI
  120. * @param string $uri
  121. */
  122. public function setRequestUri($uri)
  123. {
  124. $this->requestUri = $uri;
  125. }
  126. public function getGroups($uid = null): array
  127. {
  128. $uid = is_null($uid) ? $this->id : $uid;
  129. return parent::getGroups($uid);
  130. }
  131. public function getAuthList($uid = null)
  132. {
  133. $uid = is_null($uid) ? $this->id : $uid;
  134. return parent::getAuthList($uid);
  135. }
  136. public function getRuleIds($uid = null): array
  137. {
  138. $uid = is_null($uid) ? $this->id : $uid;
  139. return parent::getRuleIds($uid);
  140. }
  141. /**
  142. * 获取管理员所属于的分组ID
  143. * @param int $uid
  144. * @return array
  145. */
  146. public function getGroupIds($uid = null)
  147. {
  148. $groups = $this->getGroups($uid);
  149. $groupIds = [];
  150. foreach ($groups as $K => $v) {
  151. $groupIds[] = (int) $v['group_id'];
  152. }
  153. return $groupIds;
  154. }
  155. /**
  156. * 用户登录
  157. * @param string $username 用户名
  158. * @param string $password 密码
  159. * @param int $keeptime
  160. * @return bool
  161. */
  162. public function login(string $username = '', string $password = '', int $keeptime = 0): bool
  163. {
  164. $username = trim($username);
  165. $password = trim($password);
  166. $admin = AdminUser::getByUsername($username);
  167. if (!$admin) {
  168. $this->setError('用户名不正确');
  169. return false;
  170. }
  171. if ($admin['status'] !== 1) {
  172. $this->setError('管理员已经被禁止登录');
  173. return false;
  174. }
  175. if (Config::get('yzn.admin_login_retry') && $admin->login_failure >= 10 && time() - $admin->getData('update_time') < 86400) {
  176. $this->setError('请于1天后再尝试登录');
  177. return false;
  178. }
  179. if ($admin->password != encrypt_password($password, $admin->encrypt)) {
  180. $admin->login_failure++;
  181. $admin->save();
  182. $this->setError('密码不正确');
  183. return false;
  184. }
  185. $admin->login_failure = 0;
  186. $admin->last_login_time = time();
  187. $admin->last_login_ip = request()->ip();
  188. $admin->token = Random::uuid();
  189. $admin->save();
  190. Session::set("admin", $admin->toArray());
  191. Session::set("admin.safecode", $this->getEncryptSafecode($admin));
  192. $this->keeplogin($admin, $keeptime);
  193. return true;
  194. }
  195. /**
  196. * 刷新保持登录的Cookie
  197. * @param $admin
  198. * @param $keeptime
  199. * @return bool
  200. */
  201. protected function keeplogin($admin, $keeptime = 0): bool
  202. {
  203. if ($keeptime) {
  204. $expiretime = time() + $keeptime;
  205. $key = $this->getKeeploginKey($admin, $keeptime, $expiretime);
  206. Cookie::set('keeplogin', implode('|', [$admin['id'], $keeptime, $expiretime, $key]), $keeptime);
  207. return true;
  208. }
  209. return false;
  210. }
  211. /**
  212. * 自动登录
  213. * @return bool
  214. * @throws \think\db\exception\DataNotFoundException
  215. * @throws \think\db\exception\DbException
  216. * @throws \think\db\exception\ModelNotFoundException
  217. */
  218. public function autologin(): bool
  219. {
  220. $keeplogin = Cookie::get('keeplogin');
  221. if (!$keeplogin) {
  222. return false;
  223. }
  224. list($id, $keeptime, $expiretime, $key) = explode('|', $keeplogin);
  225. if ($id && $keeptime && $expiretime && $key && $expiretime > time()) {
  226. $admin = AdminUser::find($id);
  227. if (!$admin || !$admin->token) {
  228. return false;
  229. }
  230. //token有变更
  231. if ($key != $this->getKeeploginKey($admin, $keeptime, $expiretime)) {
  232. return false;
  233. }
  234. $ip = request()->ip();
  235. //IP有变动
  236. if ($admin->last_login_ip != $ip) {
  237. return false;
  238. }
  239. Session::set("admin", $admin->toArray());
  240. Session::set("admin.safecode", $this->getEncryptSafecode($admin));
  241. //刷新自动登录的时效
  242. $this->keeplogin($admin, $keeptime);
  243. return true;
  244. } else {
  245. return false;
  246. }
  247. }
  248. /**
  249. * 检验用户是否已经登陆
  250. * @return bool
  251. * @throws \think\db\exception\DataNotFoundException
  252. * @throws \think\db\exception\DbException
  253. * @throws \think\db\exception\ModelNotFoundException
  254. */
  255. public function isLogin(): bool
  256. {
  257. if ($this->logined) {
  258. return true;
  259. }
  260. $admin = Session::get('admin');
  261. if (!$admin) {
  262. return false;
  263. }
  264. $my = AdminUser::find($admin['id']);
  265. if (!$my) {
  266. return false;
  267. }
  268. //校验安全码,可用于判断关键信息发生了变更需要重新登录
  269. if (!isset($admin['safecode']) || $this->getEncryptSafecode($my) !== $admin['safecode']) {
  270. $this->logout();
  271. return false;
  272. }
  273. //判断是否同一时间同一账号只能在一个地方登录
  274. if (Config::get('yzn.admin_login_unique')) {
  275. if ($my['token'] != $admin['token']) {
  276. $this->logout();
  277. return false;
  278. }
  279. }
  280. //判断管理员IP是否变动
  281. if (Config::get('yzn.admin_loginip_check')) {
  282. if (!isset($admin['last_login_ip']) || $admin['last_login_ip'] != request()->ip()) {
  283. $this->logout();
  284. return false;
  285. }
  286. }
  287. $this->logined = true;
  288. return true;
  289. }
  290. /**
  291. * 检查当前用户是否超级管理员
  292. * @return bool
  293. */
  294. public function isAdministrator(): bool
  295. {
  296. return in_array('*', $this->getRuleIds());
  297. }
  298. /**
  299. * 获取自动登录Key
  300. * @param $params
  301. * @param $keeptime
  302. * @param $expiretime
  303. * @return string
  304. */
  305. public function getKeeploginKey($params, $keeptime, $expiretime)
  306. {
  307. return md5(md5($params['id']) . md5($keeptime) . md5($expiretime) . $params['token'] . Config::get('token.key'));
  308. }
  309. /**
  310. * 获取加密后的安全码
  311. * @param $params
  312. * @return string
  313. */
  314. public function getEncryptSafecode($params)
  315. {
  316. return md5(md5($params['username']) . md5(substr($params['password'], 0, 6)) . Config::get('token.key'));
  317. }
  318. /**
  319. * 检测当前控制器和方法是否匹配传递的数组
  320. *
  321. * @param array $arr 需要验证权限的数组
  322. * @return bool
  323. */
  324. public function match($arr = [])
  325. {
  326. $request = Request::instance();
  327. $arr = is_array($arr) ? $arr : explode(',', $arr);
  328. if (!$arr) {
  329. return false;
  330. }
  331. $arr = array_map('strtolower', $arr);
  332. // 是否存在
  333. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  334. return true;
  335. }
  336. // 没找到匹配
  337. return false;
  338. }
  339. /**
  340. * 注销登录
  341. */
  342. public function logout()
  343. {
  344. $admin = AdminUser::find(intval($this->id));
  345. if ($admin) {
  346. $admin->token = '';
  347. $admin->save();
  348. }
  349. $this->logined = false; //重置登录状态
  350. Session::delete("admin");
  351. Cookie::delete("keeplogin");
  352. return true;
  353. }
  354. public function getSidebar($params = [])
  355. {
  356. $params = array_merge($params, ...Event::trigger("admin_sidebar_begin"));
  357. $colorArr = ['red', 'orange', 'green', 'cyan', 'black', 'gray', 'blue'];
  358. $colorNums = count($colorArr);
  359. $badgeList = [];
  360. // 生成菜单的badge
  361. foreach ($params as $k => $v) {
  362. $url = $k;
  363. if (is_array($v)) {
  364. $nums = $v[0] ?? 0;
  365. $color = $v[1] ?? $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  366. $class = $v[2] ?? 'layui-badge';
  367. } else {
  368. $nums = $v;
  369. $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  370. $class = 'layui-badge';
  371. }
  372. //必须nums大于0才显示
  373. if ($nums) {
  374. $badgeList[$url] = '<small class="' . $class . ' layui-bg-' . $color . '">' . $nums . '</small>';
  375. }
  376. }
  377. // 读取管理员当前拥有的权限节点
  378. $userRule = $this->getAuthList();
  379. // 必须将结果集转换为数组
  380. $ruleList = \app\admin\model\AuthRule::where('status', 1)
  381. ->where('ismenu', 1)
  382. ->order('listorder', 'desc')
  383. ->cache("__menu__")
  384. ->select()->toArray();
  385. $indexRuleList = \app\admin\model\AuthRule::where('status', 1)
  386. ->where('ismenu', 0)
  387. ->where('name', 'like', '%/index')
  388. ->column('name,parentid');
  389. $pidArr = array_unique(array_filter(array_column($ruleList, 'parentid')));
  390. foreach ($ruleList as $k => &$v) {
  391. if (!in_array(strtolower($v['name']), $userRule)) {
  392. unset($ruleList[$k]);
  393. continue;
  394. }
  395. $indexRuleName = $v['name'] . '/index';
  396. if (isset($indexRuleList[$indexRuleName]) && !in_array($indexRuleName, $userRule)) {
  397. unset($ruleList[$k]);
  398. continue;
  399. }
  400. $v['openType'] = $v['menutype']; //兼容前端
  401. $v['type'] = $v['ismenu']; //兼容前端
  402. $v['badge'] = $badgeList[$v['name']] ?? '';
  403. $v['href'] = isset($v['url']) && $v['url'] ? $v['url'] : '/' . $v['name'];
  404. $v['href'] = preg_match("/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i", $v['href']) ? $v['href'] : (string) url($v['href'], [], false);
  405. }
  406. $lastArr = array_unique(array_filter(array_column($ruleList, 'parentid')));
  407. $pidDiffArr = array_diff($pidArr, $lastArr);
  408. foreach ($ruleList as $index => $item) {
  409. if (in_array($item['id'], $pidDiffArr)) {
  410. unset($ruleList[$index]);
  411. }
  412. }
  413. // 构造菜单数据
  414. Tree::instance()->init($ruleList);
  415. return Tree::instance()->getTreeArray(0);
  416. }
  417. /**
  418. * 获取错误信息
  419. * @access public
  420. * @return mixed
  421. */
  422. public function getError()
  423. {
  424. return $this->error ?: '';
  425. }
  426. /**
  427. * 设置错误信息
  428. *
  429. * @param string $error 错误信息
  430. * @return Auth
  431. */
  432. public function setError($error)
  433. {
  434. $this->error = $error;
  435. return $this;
  436. }
  437. }