Auth.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. var_dump($this->model);die;
  342. if (!$this->model) return [];
  343. $info = $this->model->toArray();
  344. $info = array_intersect_key($info, array_flip($this->getAllowFields()));
  345. $info['token'] = $this->getToken();
  346. $info['refresh_token'] = $this->getRefreshToken();
  347. return $info;
  348. }
  349. /**
  350. * 获取允许输出字段
  351. * @return array
  352. */
  353. public function getAllowFields(): array
  354. {
  355. return $this->allowFields;
  356. }
  357. /**
  358. * 设置允许输出字段
  359. * @param $fields
  360. * @return void
  361. */
  362. public function setAllowFields($fields): void
  363. {
  364. $this->allowFields = $fields;
  365. }
  366. /**
  367. * 设置Token有效期
  368. * @param int $keepTime
  369. * @return void
  370. */
  371. public function setKeepTime(int $keepTime = 0): void
  372. {
  373. $this->keepTime = $keepTime;
  374. }
  375. public function check(string $name, int $uid = 0, string $relation = 'or', string $mode = 'url'): bool
  376. {
  377. return parent::check($name, $uid ?: $this->id, $relation, $mode);
  378. }
  379. public function getGroups(int $uid = 0): array
  380. {
  381. return parent::getGroups($uid ?: $this->id);
  382. }
  383. public function getRuleList(int $uid = 0): array
  384. {
  385. return parent::getRuleList($uid ?: $this->id);
  386. }
  387. public function getRuleIds(int $uid = 0): array
  388. {
  389. return parent::getRuleIds($uid ?: $this->id);
  390. }
  391. public function getMenus(int $uid = 0): array
  392. {
  393. return parent::getMenus($uid ?: $this->id);
  394. }
  395. /**
  396. * 是否是超级管理员
  397. * @throws Throwable
  398. */
  399. public function isSuperAdmin(): bool
  400. {
  401. return in_array('*', $this->getRuleIds());
  402. }
  403. /**
  404. * 获取管理员所在分组的所有子级分组
  405. * @return array
  406. * @throws Throwable
  407. */
  408. public function getAdminChildGroups(): array
  409. {
  410. $groupIds = Db::name('admin_group_access')
  411. ->where('uid', $this->id)
  412. ->select();
  413. $children = [];
  414. foreach ($groupIds as $group) {
  415. $this->getGroupChildGroups($group['group_id'], $children);
  416. }
  417. return array_unique($children);
  418. }
  419. /**
  420. * 获取一个分组下的子分组
  421. * @param int $groupId 分组ID
  422. * @param array $children 存放子分组的变量
  423. * @return void
  424. * @throws Throwable
  425. */
  426. public function getGroupChildGroups(int $groupId, array &$children): void
  427. {
  428. $childrenTemp = AdminGroup::where('pid', $groupId)
  429. ->where('status', '1')
  430. ->select();
  431. foreach ($childrenTemp as $item) {
  432. $children[] = $item['id'];
  433. $this->getGroupChildGroups($item['id'], $children);
  434. }
  435. }
  436. /**
  437. * 获取分组内的管理员
  438. * @param array $groups
  439. * @return array 管理员数组
  440. */
  441. public function getGroupAdmins(array $groups): array
  442. {
  443. return Db::name('admin_group_access')
  444. ->where('group_id', 'in', $groups)
  445. ->column('uid');
  446. }
  447. /**
  448. * 获取拥有"所有权限"的分组
  449. * @param string $dataLimit 数据权限
  450. * @return array 分组数组
  451. * @throws Throwable
  452. */
  453. public function getAllAuthGroups(string $dataLimit): array
  454. {
  455. // 当前管理员拥有的权限
  456. $rules = $this->getRuleIds();
  457. $allAuthGroups = [];
  458. $groups = AdminGroup::where('status', '1')->select();
  459. foreach ($groups as $group) {
  460. if ($group['rules'] == '*') {
  461. continue;
  462. }
  463. $groupRules = explode(',', $group['rules']);
  464. // 及时break, array_diff 等没有 in_array 快
  465. $all = true;
  466. foreach ($groupRules as $groupRule) {
  467. if (!in_array($groupRule, $rules)) {
  468. $all = false;
  469. break;
  470. }
  471. }
  472. if ($all) {
  473. if ($dataLimit == 'allAuth' || ($dataLimit == 'allAuthAndOthers' && array_diff($rules, $groupRules))) {
  474. $allAuthGroups[] = $group['id'];
  475. }
  476. }
  477. }
  478. return $allAuthGroups;
  479. }
  480. /**
  481. * 设置错误消息
  482. * @param $error
  483. * @return Auth
  484. */
  485. public function setError($error): Auth
  486. {
  487. $this->error = $error;
  488. return $this;
  489. }
  490. /**
  491. * 获取错误消息
  492. * @return string
  493. */
  494. public function getError(): string
  495. {
  496. return $this->error ? __($this->error) : '';
  497. }
  498. /**
  499. * 属性重置(注销、登录失败、重新初始化等将单例数据销毁)
  500. */
  501. protected function reset(bool $deleteToken = true): bool
  502. {
  503. if ($deleteToken && $this->token) {
  504. Token::delete($this->token);
  505. }
  506. $this->token = '';
  507. $this->loginEd = false;
  508. $this->model = null;
  509. $this->refreshToken = '';
  510. $this->setError('');
  511. $this->setKeepTime((int)Config::get('buildadmin.admin_token_keep_time'));
  512. return true;
  513. }
  514. }