Auth.php 15 KB

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