Auth.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. if(Cache::get('admin_only'.$username))
  196. {
  197. $other = Cache::get('admin_only'.$username);
  198. Cache::delete($other);
  199. Cache::delete('admin_only'.$username);
  200. }
  201. $token = $this->getToken();
  202. Cache::set('admin_only'.$username,$token);
  203. Cache::set($token,time());
  204. return true;
  205. }
  206. public function loginByToken(string $token)
  207. {
  208. $data = Cache::get($token);
  209. if(empty($data))
  210. {
  211. $this->setError('过期的token');
  212. return '';
  213. }
  214. $code = $data['orgCode'];
  215. $institution = Db::name('institution')->where('institution_code',$code)->find();
  216. if(empty($institution))
  217. {
  218. $this->setError('无效的机构码');
  219. return '';
  220. }
  221. $string = time().rand(0,9999);
  222. Cache::set($string,$token,8640);
  223. $arr['userInfo'] = [
  224. 'avatar'=>'/storage/default/20240918/8587087c718ab44a3b2a24b4584ff8321c7ecde8801f393.jpg',
  225. 'id'=>1,
  226. 'last_login_time'=>date('Y-m-d H:i:s'),
  227. 'nickname'=>$institution['name'],
  228. 'refresh_token'=>'',
  229. 'token'=>$string,
  230. 'username'=>$institution['name']
  231. ];
  232. // Token::set($string, self::TOKEN_TYPE . '-refresh', 1, 3600);
  233. return $arr;
  234. }
  235. /**
  236. * 设置刷新Token
  237. * @param int $keepTime
  238. */
  239. public function setRefreshToken(int $keepTime = 0): void
  240. {
  241. $this->refreshToken = Random::uuid();
  242. Token::set($this->refreshToken, self::TOKEN_TYPE . '-refresh', $this->model->ID, $keepTime);
  243. }
  244. /**
  245. * 管理员登录成功
  246. * @return bool
  247. */
  248. public function loginSuccessful(): bool
  249. {
  250. if (!$this->model) return false;
  251. $this->model->startTrans();
  252. try {
  253. $this->model->LOGIN_FAILURE = 0;
  254. $this->model->LAST_LOGIN_TIME = time();
  255. $this->model->LAST_LOGIN_IP = request()->ip();
  256. $this->model->save();
  257. $this->loginEd = true;
  258. if (!$this->token) {
  259. $this->token = Random::uuid();
  260. Token::set($this->token, self::TOKEN_TYPE, $this->model->ID, $this->keepTime);
  261. }
  262. $this->model->commit();
  263. } catch (Throwable $e) {
  264. $this->model->rollback();
  265. $this->setError($e->getMessage());
  266. return false;
  267. }
  268. return true;
  269. }
  270. /**
  271. * 管理员登录失败
  272. * @return bool
  273. */
  274. public function loginFailed(): bool
  275. {
  276. if (!$this->model) return false;
  277. $this->model->startTrans();
  278. try {
  279. $this->model->LOGIN_FAILURE++;
  280. $this->model->LAST_LOGIN_TIME = time();
  281. $this->model->LAST_LOGIN_IP = request()->ip();
  282. $this->model->save();
  283. $this->model->commit();
  284. } catch (Throwable $e) {
  285. $this->model->rollback();
  286. $this->setError($e->getMessage());
  287. return false;
  288. }
  289. return $this->reset();
  290. }
  291. /**
  292. * 退出登录
  293. * @return bool
  294. */
  295. public function logout(): bool
  296. {
  297. if (!$this->loginEd) {
  298. $this->setError('You are not logged in');
  299. return false;
  300. }
  301. return $this->reset();
  302. }
  303. /**
  304. * 是否登录
  305. * @return bool
  306. */
  307. public function isLogin(): bool
  308. {
  309. return $this->loginEd;
  310. }
  311. /**
  312. * 获取管理员模型
  313. * @return Admin
  314. */
  315. public function getAdmin(): Admin
  316. {
  317. return $this->model;
  318. }
  319. /**
  320. * 获取管理员Token
  321. * @return string
  322. */
  323. public function getToken(): string
  324. {
  325. return $this->token;
  326. }
  327. /**
  328. * 获取管理员刷新Token
  329. * @return string
  330. */
  331. public function getRefreshToken(): string
  332. {
  333. return $this->refreshToken;
  334. }
  335. /**
  336. * 获取管理员信息 - 只输出允许输出的字段
  337. * @return array
  338. */
  339. public function getInfo(): array
  340. {
  341. if (!$this->model) return [];
  342. $info = $this->model->toArray();
  343. $info = array_intersect_key($info, array_flip($this->getAllowFields()));
  344. $info['token'] = $this->getToken();
  345. $info['refresh_token'] = $this->getRefreshToken();
  346. return $info;
  347. }
  348. /**
  349. * 获取允许输出字段
  350. * @return array
  351. */
  352. public function getAllowFields(): array
  353. {
  354. return $this->allowFields;
  355. }
  356. /**
  357. * 设置允许输出字段
  358. * @param $fields
  359. * @return void
  360. */
  361. public function setAllowFields($fields): void
  362. {
  363. $this->allowFields = $fields;
  364. }
  365. /**
  366. * 设置Token有效期
  367. * @param int $keepTime
  368. * @return void
  369. */
  370. public function setKeepTime(int $keepTime = 0): void
  371. {
  372. $this->keepTime = $keepTime;
  373. }
  374. public function check(string $name, int $uid = 0, string $relation = 'or', string $mode = 'url'): bool
  375. {
  376. return parent::check($name, $uid ?: $this->ID, $relation, $mode);
  377. }
  378. public function getGroups(int $uid = 0): array
  379. {
  380. return parent::getGroups($uid ?: $this->ID);
  381. }
  382. public function getRuleList(int $uid = 0): array
  383. {
  384. return parent::getRuleList($uid ?: $this->ID);
  385. }
  386. public function getRuleIds(int $uid = 0): array
  387. {
  388. return parent::getRuleIds($uid ?: $this->ID);
  389. }
  390. public function getMenus(int $uid = 0): array
  391. {
  392. return parent::getMenus($uid ?: $this->ID);
  393. }
  394. /**
  395. * 是否是超级管理员
  396. * @throws Throwable
  397. */
  398. public function isSuperAdmin(): bool
  399. {
  400. return in_array('*', $this->getRuleIds());
  401. }
  402. /**
  403. * 获取管理员所在分组的所有子级分组
  404. * @return array
  405. * @throws Throwable
  406. */
  407. public function getAdminChildGroups(): array
  408. {
  409. $groupIds = Db::name('admin_group_access')
  410. ->where('uid', $this->ID)
  411. ->select();
  412. $children = [];
  413. foreach ($groupIds as $group) {
  414. $this->getGroupChildGroups($group['group_id'], $children);
  415. }
  416. return array_unique($children);
  417. }
  418. /**
  419. * 获取一个分组下的子分组
  420. * @param int $groupId 分组ID
  421. * @param array $children 存放子分组的变量
  422. * @return void
  423. * @throws Throwable
  424. */
  425. public function getGroupChildGroups(int $groupId, array &$children): void
  426. {
  427. $childrenTemp = AdminGroup::where('pid', $groupId)
  428. ->where('status', '1')
  429. ->select();
  430. foreach ($childrenTemp as $item) {
  431. $children[] = $item['id'];
  432. $this->getGroupChildGroups($item['id'], $children);
  433. }
  434. }
  435. /**
  436. * 获取分组内的管理员
  437. * @param array $groups
  438. * @return array 管理员数组
  439. */
  440. public function getGroupAdmins(array $groups): array
  441. {
  442. return Db::name('admin_group_access')
  443. ->where('group_id', 'in', $groups)
  444. ->column('uid');
  445. }
  446. /**
  447. * 获取拥有"所有权限"的分组
  448. * @param string $dataLimit 数据权限
  449. * @return array 分组数组
  450. * @throws Throwable
  451. */
  452. public function getAllAuthGroups(string $dataLimit): array
  453. {
  454. // 当前管理员拥有的权限
  455. $rules = $this->getRuleIds();
  456. $allAuthGroups = [];
  457. $groups = AdminGroup::where('status', '1')->select();
  458. foreach ($groups as $group) {
  459. if ($group['rules'] == '*') {
  460. continue;
  461. }
  462. $groupRules = explode(',', $group['rules']);
  463. // 及时break, array_diff 等没有 in_array 快
  464. $all = true;
  465. foreach ($groupRules as $groupRule) {
  466. if (!in_array($groupRule, $rules)) {
  467. $all = false;
  468. break;
  469. }
  470. }
  471. if ($all) {
  472. if ($dataLimit == 'allAuth' || ($dataLimit == 'allAuthAndOthers' && array_diff($rules, $groupRules))) {
  473. $allAuthGroups[] = $group['id'];
  474. }
  475. }
  476. }
  477. return $allAuthGroups;
  478. }
  479. /**
  480. * 设置错误消息
  481. * @param $error
  482. * @return Auth
  483. */
  484. public function setError($error): Auth
  485. {
  486. $this->error = $error;
  487. return $this;
  488. }
  489. /**
  490. * 获取错误消息
  491. * @return string
  492. */
  493. public function getError(): string
  494. {
  495. return $this->error ? __($this->error) : '';
  496. }
  497. /**
  498. * 属性重置(注销、登录失败、重新初始化等将单例数据销毁)
  499. */
  500. protected function reset(bool $deleteToken = true): bool
  501. {
  502. if ($deleteToken && $this->token) {
  503. Token::delete($this->token);
  504. }
  505. $this->token = '';
  506. $this->loginEd = false;
  507. $this->model = null;
  508. $this->refreshToken = '';
  509. $this->setError('');
  510. $this->setKeepTime((int)Config::get('buildadmin.admin_token_keep_time'));
  511. return true;
  512. }
  513. }