Auth.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. <?php
  2. namespace app\admin\library;
  3. use think\facade\Cache;
  4. use Throwable;
  5. use ba\Random;
  6. use think\facade\Db;
  7. use think\facade\Config;
  8. use app\admin\model\Admin;
  9. use app\common\facade\Token;
  10. use app\admin\model\AdminGroup;
  11. /**
  12. * 管理员权限类
  13. * @property int $id 管理员ID
  14. * @property string $username 管理员用户名
  15. * @property string $nickname 管理员昵称
  16. * @property string $email 管理员邮箱
  17. * @property string $mobile 管理员手机号
  18. */
  19. class Auth extends \ba\Auth
  20. {
  21. /**
  22. * 需要登录时/无需登录时的响应状态代码
  23. */
  24. public const LOGIN_RESPONSE_CODE = 303;
  25. /**
  26. * 需要登录标记 - 前台应清理 token、记录当前路由 path、跳转到登录页
  27. */
  28. public const NEED_LOGIN = 'need login';
  29. /**
  30. * 已经登录标记 - 前台应跳转到基础路由
  31. */
  32. public const LOGGED_IN = 'logged in';
  33. /**
  34. * token 入库 type
  35. */
  36. public const TOKEN_TYPE = 'admin';
  37. /**
  38. * 是否登录
  39. * @var bool
  40. */
  41. protected bool $loginEd = false;
  42. /**
  43. * 错误消息
  44. * @var string
  45. */
  46. protected string $error = '';
  47. /**
  48. * Model实例
  49. * @var ?Admin
  50. */
  51. protected ?Admin $model = null;
  52. /**
  53. * 令牌
  54. * @var string
  55. */
  56. protected string $token = '';
  57. /**
  58. * 刷新令牌
  59. * @var string
  60. */
  61. protected string $refreshToken = '';
  62. /**
  63. * 令牌默认有效期
  64. * 可在 config/buildadmin.php 内修改默认值
  65. * @var int
  66. */
  67. protected int $keepTime = 86400;
  68. /**
  69. * 刷新令牌有效期
  70. * @var int
  71. */
  72. protected int $refreshTokenKeepTime = 2592000;
  73. /**
  74. * 允许输出的字段
  75. * @var array
  76. */
  77. protected array $allowFields = ['id', 'username', 'nickname', 'avatar', 'last_login_time','depart','depart_id','institution','institution_id'];
  78. public function __construct(array $config = [])
  79. {
  80. parent::__construct($config);
  81. $this->setKeepTime((int)Config::get('buildadmin.admin_token_keep_time'));
  82. }
  83. /**
  84. * 魔术方法-管理员信息字段
  85. * @param $name
  86. * @return mixed 字段信息
  87. */
  88. public function __get($name): mixed
  89. {
  90. return $this->model?->$name;
  91. }
  92. /**
  93. * 初始化
  94. * @access public
  95. * @param array $options 传递到 /ba/Auth 的配置信息
  96. * @return Auth
  97. */
  98. public static function instance(array $options = []): Auth
  99. {
  100. $request = request();
  101. if (!isset($request->adminAuth)) {
  102. $request->adminAuth = new static($options);
  103. }
  104. return $request->adminAuth;
  105. }
  106. /**
  107. * 根据Token初始化管理员登录态
  108. * @param string $token
  109. * @return bool
  110. * @throws Throwable
  111. */
  112. public function init(string $token): bool
  113. {
  114. $tokenData = Token::get($token);
  115. if ($tokenData) {
  116. /**
  117. * 过期检查,过期则抛出 @see TokenExpirationException
  118. */
  119. Token::tokenExpirationCheck($tokenData);
  120. $userId = intval($tokenData['user_id']);
  121. if ($tokenData['type'] == self::TOKEN_TYPE && $userId > 0) {
  122. $this->model = Admin::where('id', $userId)->find();
  123. if (!$this->model) {
  124. $this->setError('Account not exist');
  125. return false;
  126. }
  127. if ($this->model['status'] != '1') {
  128. $this->setError('Account disabled');
  129. return false;
  130. }
  131. $this->token = $token;
  132. $this->loginSuccessful();
  133. return true;
  134. }
  135. }
  136. $this->setError('Token login failed');
  137. $this->reset();
  138. return false;
  139. }
  140. /**
  141. * 管理员登录
  142. * @param string $username 用户名
  143. * @param string $password 密码
  144. * @param bool $keep 是否保持登录
  145. * @return bool
  146. * @throws Throwable
  147. */
  148. public function login(string $username, string $password, bool $keep = false,&$force=0,&$userId='')//: bool
  149. {
  150. $this->model = Admin::where('username', $username)->find();
  151. if (!$this->model) {
  152. $this->setError('Username is incorrect');
  153. return false;
  154. }
  155. if ($this->model->STATUS == '0') {
  156. $this->setError('Account disabled');
  157. return false;
  158. }
  159. $adminLoginRetry = Config::get('buildadmin.admin_login_retry');
  160. if ($adminLoginRetry && $this->model->LOGIN_FAILURE >= $adminLoginRetry && time() - $this->model->getData('last_login_time') < 86400) {
  161. $this->setError('Please try again after 1 day');
  162. return false;
  163. }
  164. if ($this->model->PASSWORD != encrypt_password($password, $this->model->SALT)) {
  165. $this->loginFailed();
  166. $this->setError('Password is incorrect');
  167. return false;
  168. }
  169. if (Config::get('buildadmin.admin_sso')) {
  170. Token::clear(self::TOKEN_TYPE, $this->model->ID);
  171. Token::clear(self::TOKEN_TYPE . '-refresh', $this->model->ID);
  172. }
  173. $userId = $this->model->ID;
  174. if($password == $username.'@Zskk2024')
  175. {
  176. $force = 3;
  177. return true;
  178. }
  179. if(empty($this->model->UPDATE_PASS_TIME))
  180. {
  181. //初始密码未更换过
  182. $force = 1;
  183. return true;
  184. }
  185. if((time()-(strtotime($this->model->UPDATE_PASS_TIME))) > 90*86400)
  186. {
  187. //密码未更新的时间超过90天
  188. $force = 2;
  189. return true;
  190. }
  191. if ($keep) {
  192. $this->setRefreshToken($this->refreshTokenKeepTime);
  193. }
  194. $a = $this->loginSuccessful();
  195. var_dump($a);die;
  196. if(Cache::get('admin_only'.$username))
  197. {
  198. $other = Cache::get('admin_only'.$username);
  199. Cache::delete($other);
  200. Cache::delete('admin_only'.$username);
  201. }
  202. $token = $this->getToken();
  203. Cache::set('admin_only'.$username,$token);
  204. Cache::set($token,time());
  205. return true;
  206. }
  207. public function loginByToken(string $token)
  208. {
  209. $data = Cache::get($token);
  210. if(empty($data))
  211. {
  212. $this->setError('过期的token');
  213. return '';
  214. }
  215. $code = $data['orgCode'];
  216. $institution = Db::name('institution')->where('institution_code',$code)->find();
  217. if(empty($institution))
  218. {
  219. $this->setError('无效的机构码');
  220. return '';
  221. }
  222. $string = time().rand(0,9999);
  223. Cache::set($string,$token,8640);
  224. $arr['userInfo'] = [
  225. 'avatar'=>'/storage/default/20240918/8587087c718ab44a3b2a24b4584ff8321c7ecde8801f393.jpg',
  226. 'id'=>1,
  227. 'last_login_time'=>date('Y-m-d H:i:s'),
  228. 'nickname'=>$institution['name'],
  229. 'refresh_token'=>'',
  230. 'token'=>$string,
  231. 'username'=>$institution['name']
  232. ];
  233. // Token::set($string, self::TOKEN_TYPE . '-refresh', 1, 3600);
  234. return $arr;
  235. }
  236. /**
  237. * 设置刷新Token
  238. * @param int $keepTime
  239. */
  240. public function setRefreshToken(int $keepTime = 0): void
  241. {
  242. $this->refreshToken = Random::uuid();
  243. Token::set($this->refreshToken, self::TOKEN_TYPE . '-refresh', $this->model->ID, $keepTime);
  244. }
  245. /**
  246. * 管理员登录成功
  247. * @return bool
  248. */
  249. public function loginSuccessful(): bool
  250. {
  251. Token::set('1',2,1,1000);
  252. var_dump(Token::get('1'));die;
  253. if (!$this->model) return false;
  254. $this->model->startTrans();
  255. try {
  256. $this->model->LOGIN_FAILURE = 0;
  257. $this->model->LAST_LOGIN_TIME = time();
  258. $this->model->LAST_LOGIN_IP = request()->ip();
  259. $this->model->save();
  260. $this->loginEd = true;
  261. if (!$this->token) {
  262. $this->token = Random::uuid();
  263. Token::set($this->token, self::TOKEN_TYPE, $this->model->ID, $this->keepTime);
  264. }
  265. $this->model->commit();
  266. } catch (Throwable $e) {
  267. $this->model->rollback();
  268. var_dump($e->getMessage());die;
  269. $this->setError($e->getMessage());
  270. return false;
  271. }
  272. return true;
  273. }
  274. /**
  275. * 管理员登录失败
  276. * @return bool
  277. */
  278. public function loginFailed(): bool
  279. {
  280. if (!$this->model) return false;
  281. $this->model->startTrans();
  282. try {
  283. $this->model->LOGIN_FAILURE++;
  284. $this->model->LAST_LOGIN_TIME = time();
  285. $this->model->LAST_LOGIN_IP = request()->ip();
  286. $this->model->save();
  287. $this->model->commit();
  288. } catch (Throwable $e) {
  289. $this->model->rollback();
  290. $this->setError($e->getMessage());
  291. return false;
  292. }
  293. return $this->reset();
  294. }
  295. /**
  296. * 退出登录
  297. * @return bool
  298. */
  299. public function logout(): bool
  300. {
  301. if (!$this->loginEd) {
  302. $this->setError('You are not logged in');
  303. return false;
  304. }
  305. return $this->reset();
  306. }
  307. /**
  308. * 是否登录
  309. * @return bool
  310. */
  311. public function isLogin(): bool
  312. {
  313. return $this->loginEd;
  314. }
  315. /**
  316. * 获取管理员模型
  317. * @return Admin
  318. */
  319. public function getAdmin(): Admin
  320. {
  321. return $this->model;
  322. }
  323. /**
  324. * 获取管理员Token
  325. * @return string
  326. */
  327. public function getToken(): string
  328. {
  329. return $this->token;
  330. }
  331. /**
  332. * 获取管理员刷新Token
  333. * @return string
  334. */
  335. public function getRefreshToken(): string
  336. {
  337. return $this->refreshToken;
  338. }
  339. /**
  340. * 获取管理员信息 - 只输出允许输出的字段
  341. * @return array
  342. */
  343. public function getInfo(): array
  344. {
  345. if (!$this->model) return [];
  346. $info = $this->model->toArray();
  347. $info = array_intersect_key($info, array_flip($this->getAllowFields()));
  348. $info['token'] = $this->getToken();
  349. $info['refresh_token'] = $this->getRefreshToken();
  350. return $info;
  351. }
  352. /**
  353. * 获取允许输出字段
  354. * @return array
  355. */
  356. public function getAllowFields(): array
  357. {
  358. return $this->allowFields;
  359. }
  360. /**
  361. * 设置允许输出字段
  362. * @param $fields
  363. * @return void
  364. */
  365. public function setAllowFields($fields): void
  366. {
  367. $this->allowFields = $fields;
  368. }
  369. /**
  370. * 设置Token有效期
  371. * @param int $keepTime
  372. * @return void
  373. */
  374. public function setKeepTime(int $keepTime = 0): void
  375. {
  376. $this->keepTime = $keepTime;
  377. }
  378. public function check(string $name, int $uid = 0, string $relation = 'or', string $mode = 'url'): bool
  379. {
  380. return parent::check($name, $uid ?: $this->id, $relation, $mode);
  381. }
  382. public function getGroups(int $uid = 0): array
  383. {
  384. return parent::getGroups($uid ?: $this->id);
  385. }
  386. public function getRuleList(int $uid = 0): array
  387. {
  388. return parent::getRuleList($uid ?: $this->id);
  389. }
  390. public function getRuleIds(int $uid = 0): array
  391. {
  392. return parent::getRuleIds($uid ?: $this->id);
  393. }
  394. public function getMenus(int $uid = 0): array
  395. {
  396. return parent::getMenus($uid ?: $this->id);
  397. }
  398. /**
  399. * 是否是超级管理员
  400. * @throws Throwable
  401. */
  402. public function isSuperAdmin(): bool
  403. {
  404. return in_array('*', $this->getRuleIds());
  405. }
  406. /**
  407. * 获取管理员所在分组的所有子级分组
  408. * @return array
  409. * @throws Throwable
  410. */
  411. public function getAdminChildGroups(): array
  412. {
  413. $groupIds = Db::name('admin_group_access')
  414. ->where('uid', $this->id)
  415. ->select();
  416. $children = [];
  417. foreach ($groupIds as $group) {
  418. $this->getGroupChildGroups($group['group_id'], $children);
  419. }
  420. return array_unique($children);
  421. }
  422. /**
  423. * 获取一个分组下的子分组
  424. * @param int $groupId 分组ID
  425. * @param array $children 存放子分组的变量
  426. * @return void
  427. * @throws Throwable
  428. */
  429. public function getGroupChildGroups(int $groupId, array &$children): void
  430. {
  431. $childrenTemp = AdminGroup::where('pid', $groupId)
  432. ->where('status', '1')
  433. ->select();
  434. foreach ($childrenTemp as $item) {
  435. $children[] = $item['id'];
  436. $this->getGroupChildGroups($item['id'], $children);
  437. }
  438. }
  439. /**
  440. * 获取分组内的管理员
  441. * @param array $groups
  442. * @return array 管理员数组
  443. */
  444. public function getGroupAdmins(array $groups): array
  445. {
  446. return Db::name('admin_group_access')
  447. ->where('group_id', 'in', $groups)
  448. ->column('uid');
  449. }
  450. /**
  451. * 获取拥有"所有权限"的分组
  452. * @param string $dataLimit 数据权限
  453. * @return array 分组数组
  454. * @throws Throwable
  455. */
  456. public function getAllAuthGroups(string $dataLimit): array
  457. {
  458. // 当前管理员拥有的权限
  459. $rules = $this->getRuleIds();
  460. $allAuthGroups = [];
  461. $groups = AdminGroup::where('status', '1')->select();
  462. foreach ($groups as $group) {
  463. if ($group['rules'] == '*') {
  464. continue;
  465. }
  466. $groupRules = explode(',', $group['rules']);
  467. // 及时break, array_diff 等没有 in_array 快
  468. $all = true;
  469. foreach ($groupRules as $groupRule) {
  470. if (!in_array($groupRule, $rules)) {
  471. $all = false;
  472. break;
  473. }
  474. }
  475. if ($all) {
  476. if ($dataLimit == 'allAuth' || ($dataLimit == 'allAuthAndOthers' && array_diff($rules, $groupRules))) {
  477. $allAuthGroups[] = $group['id'];
  478. }
  479. }
  480. }
  481. return $allAuthGroups;
  482. }
  483. /**
  484. * 设置错误消息
  485. * @param $error
  486. * @return Auth
  487. */
  488. public function setError($error): Auth
  489. {
  490. $this->error = $error;
  491. return $this;
  492. }
  493. /**
  494. * 获取错误消息
  495. * @return string
  496. */
  497. public function getError(): string
  498. {
  499. return $this->error ? __($this->error) : '';
  500. }
  501. /**
  502. * 属性重置(注销、登录失败、重新初始化等将单例数据销毁)
  503. */
  504. protected function reset(bool $deleteToken = true): bool
  505. {
  506. if ($deleteToken && $this->token) {
  507. Token::delete($this->token);
  508. }
  509. $this->token = '';
  510. $this->loginEd = false;
  511. $this->model = null;
  512. $this->refreshToken = '';
  513. $this->setError('');
  514. $this->setKeepTime((int)Config::get('buildadmin.admin_token_keep_time'));
  515. return true;
  516. }
  517. }