Auth.php 15 KB

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