Auth.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. <?php
  2. namespace app\common\library;
  3. use ba\Random;
  4. use think\Exception;
  5. use think\facade\Db;
  6. use think\facade\Event;
  7. use think\facade\Config;
  8. use app\common\model\User;
  9. use think\facade\Validate;
  10. use app\common\facade\Token;
  11. use think\db\exception\DbException;
  12. use think\db\exception\PDOException;
  13. use think\db\exception\DataNotFoundException;
  14. use think\db\exception\ModelNotFoundException;
  15. /**
  16. * 公共权限类(会员权限类)
  17. */
  18. class Auth extends \ba\Auth
  19. {
  20. /**
  21. * @var Auth 对象实例
  22. */
  23. protected static $instance;
  24. /**
  25. * @var bool 是否登录
  26. */
  27. protected $logined = false;
  28. /**
  29. * @var string 错误消息
  30. */
  31. protected $error = '';
  32. /**
  33. * @var User Model实例
  34. */
  35. protected $model = null;
  36. /**
  37. * @var string 令牌
  38. */
  39. protected $token = '';
  40. /**
  41. * @var string 刷新令牌
  42. */
  43. protected $refreshToken = '';
  44. /**
  45. * @var int 令牌默认有效期
  46. */
  47. protected $keeptime = 86400;
  48. /**
  49. * @var string[] 允许输出的字段
  50. */
  51. protected $allowFields = ['id', 'username', 'nickname', 'email', 'mobile', 'avatar', 'gender', 'birthday', 'money', 'score', 'jointime', 'motto', 'lastlogintime', 'lastloginip'];
  52. public function __construct(array $config = [])
  53. {
  54. parent::__construct(array_merge([
  55. 'auth_group' => 'user_group', // 用户组数据表名
  56. 'auth_group_access' => '', // 用户-用户组关系表(关系字段)
  57. 'auth_rule' => 'user_rule', // 权限规则表
  58. ], $config));
  59. }
  60. /**
  61. * 魔术方法-会员信息字段
  62. * @param $name
  63. * @return null|string 字段信息
  64. */
  65. public function __get($name)
  66. {
  67. return $this->model ? $this->model->$name : null;
  68. }
  69. /**
  70. * 初始化
  71. * @access public
  72. * @param array $options 参数
  73. * @return Auth
  74. */
  75. public static function instance(array $options = []): Auth
  76. {
  77. if (is_null(self::$instance)) {
  78. self::$instance = new static($options);
  79. }
  80. return self::$instance;
  81. }
  82. /**
  83. * 根据Token初始化会员登录态
  84. * @param $token
  85. * @return bool
  86. * @throws DataNotFoundException
  87. * @throws DbException
  88. * @throws ModelNotFoundException
  89. */
  90. public function init($token): bool
  91. {
  92. if ($this->logined) {
  93. return true;
  94. }
  95. if ($this->error) {
  96. return false;
  97. }
  98. $tokenData = Token::get($token);
  99. if (!$tokenData) {
  100. return false;
  101. }
  102. $userId = intval($tokenData['user_id']);
  103. if ($tokenData['type'] == 'user' && $userId > 0) {
  104. $this->model = User::where('id', $userId)->find();
  105. if (!$this->model) {
  106. $this->setError('Account not exist');
  107. return false;
  108. }
  109. if ($this->model['status'] != 'enable') {
  110. $this->setError('Account disabled');
  111. return false;
  112. }
  113. $this->token = $token;
  114. $this->loginSuccessful();
  115. return true;
  116. } else {
  117. $this->setError('Token login failed');
  118. return false;
  119. }
  120. }
  121. /**
  122. * 会员注册
  123. * @param string $username
  124. * @param string $password
  125. * @param string $mobile
  126. * @param string $email
  127. * @param int $group
  128. * @param array $extend
  129. * @return bool
  130. */
  131. public function register(string $username, string $password, string $mobile = '', string $email = '', int $group = 1, array $extend = []): bool
  132. {
  133. $validate = Validate::rule([
  134. 'mobile' => 'mobile|unique:user',
  135. 'email' => 'email|unique:user',
  136. 'username' => 'regex:^[a-zA-Z][a-zA-Z0-9_]{2,15}$|unique:user',
  137. 'password' => 'regex:^(?!.*[&<>"\'\n\r]).{6,32}$',
  138. ]);
  139. $params = [
  140. 'username' => $username,
  141. 'password' => $password,
  142. 'mobile' => $mobile,
  143. 'email' => $email,
  144. ];
  145. if (!$validate->check($params)) {
  146. $this->setError('Registration parameter error');
  147. return false;
  148. }
  149. $ip = request()->ip();
  150. $time = time();
  151. $salt = Random::build('alnum', 16);
  152. $data = [
  153. 'password' => encrypt_password($password, $salt),
  154. 'group_id' => $group,
  155. 'nickname' => preg_match("/^1[3-9]\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
  156. 'joinip' => $ip,
  157. 'jointime' => $time,
  158. 'lastloginip' => $ip,
  159. 'lastlogintime' => $time,
  160. 'salt' => $salt,
  161. 'status' => 'enable',
  162. ];
  163. $data = array_merge($params, $data);
  164. $data = array_merge($data, $extend);
  165. Db::startTrans();
  166. try {
  167. $this->model = User::create($data);
  168. $this->token = Random::uuid();
  169. Token::set($this->token, 'user', $this->model->id, $this->keeptime);
  170. Event::trigger('userRegisterSuccessed', $this->model);
  171. Db::commit();
  172. } catch (PDOException|Exception $e) {
  173. $this->setError($e->getMessage());
  174. Db::rollback();
  175. return false;
  176. }
  177. return true;
  178. }
  179. /**
  180. * 会员登录
  181. * @param string $username
  182. * @param string $password
  183. * @param bool $keeptime
  184. * @return bool
  185. * @throws DataNotFoundException
  186. * @throws DbException
  187. * @throws ModelNotFoundException
  188. */
  189. public function login(string $username, string $password, bool $keeptime): bool
  190. {
  191. // 判断账户类型
  192. $accountType = false;
  193. $validate = Validate::rule([
  194. 'mobile' => 'mobile',
  195. 'email' => 'email',
  196. 'username' => 'regex:^[a-zA-Z][a-zA-Z0-9_]{2,15}$',
  197. ]);
  198. if ($validate->check(['mobile' => $username])) $accountType = 'mobile';
  199. if ($validate->check(['email' => $username])) $accountType = 'email';
  200. if ($validate->check(['username' => $username])) $accountType = 'username';
  201. if (!$accountType) {
  202. $this->setError('Account not exist');
  203. return false;
  204. }
  205. $this->model = User::where($accountType, $username)->find();
  206. if (!$this->model) {
  207. $this->setError('Account not exist');
  208. return false;
  209. }
  210. if ($this->model['status'] == 'disable') {
  211. $this->setError('Account disabled');
  212. return false;
  213. }
  214. $userLoginRetry = Config::get('buildadmin.user_login_retry');
  215. if ($userLoginRetry && $this->model->loginfailure >= $userLoginRetry && time() - $this->model->lastlogintime < 86400) {
  216. $this->setError('Please try again after 1 day');
  217. return false;
  218. }
  219. if ($this->model->password != encrypt_password($password, $this->model->salt)) {
  220. $this->loginFailed();
  221. $this->setError('Password is incorrect');
  222. return false;
  223. }
  224. if (Config::get('buildadmin.user_sso')) {
  225. Token::clear('user', $this->model->id);
  226. Token::clear('user-refresh', $this->model->id);
  227. }
  228. if ($keeptime) {
  229. $this->setRefreshToken(2592000);
  230. }
  231. $this->loginSuccessful();
  232. return true;
  233. }
  234. /** 判断微信账胡是否注册
  235. * @param string $openid
  236. * @param string $unionid
  237. * @return bool
  238. * @throws \think\db\exception\DataNotFoundException
  239. * @throws \think\db\exception\DbException
  240. * @throws \think\db\exception\ModelNotFoundException
  241. */
  242. public function isWxUser(string $openid,string $unionid,bool $keeptime): bool
  243. {
  244. if($openid=='')return false;
  245. $this->model = User::where(['openid'=>$openid,"unionid"=>$unionid])->find();
  246. if (!$this->model) {
  247. $this->setError('Account not exist');
  248. return false;
  249. }
  250. if ($this->model['status'] == 'disable') {
  251. $this->setError('Account disabled');
  252. return false;
  253. }
  254. $userLoginRetry = Config::get('buildadmin.user_login_retry');
  255. if ($userLoginRetry && $this->model->loginfailure >= $userLoginRetry && time() - $this->model->lastlogintime < 86400) {
  256. $this->setError('Please try again after 1 day');
  257. return false;
  258. }
  259. if (Config::get('buildadmin.user_sso')) {
  260. Token::clear('user', $this->model->id);
  261. Token::clear('user-refresh', $this->model->id);
  262. }
  263. if ($keeptime) {
  264. $this->setRefreshToken(2592000);
  265. }
  266. $this->loginSuccessful();
  267. return true;
  268. }
  269. public function WxRegister(string $openid, string $unionid,string $nickname='', string $mobile='',string $avatar='',
  270. $group=1,array $extend=[]){
  271. $validate = Validate::rule([
  272. 'openid' => 'require|unique:user,openid^unionid',
  273. 'unionid' => 'max:255',
  274. ]);
  275. $params = [
  276. 'nickname' => $nickname,
  277. 'openid' => $openid,
  278. 'mobile' => $mobile,
  279. 'unionid' => $unionid,
  280. 'avatar' => $avatar,
  281. ];
  282. if (!$validate->check($params)) {
  283. $this->setError('Registration parameter error');
  284. return false;
  285. }
  286. $ip = request()->ip();
  287. $time = time();
  288. $salt = Random::build('alnum', 16);
  289. $data = [
  290. 'password' => '',
  291. 'group_id' => $group,
  292. 'joinip' => $ip,
  293. 'jointime' => $time,
  294. 'lastloginip' => $ip,
  295. 'lastlogintime' => $time,
  296. 'salt' => $salt,
  297. 'status' => 'enable',
  298. ];
  299. $data = array_merge($params, $data);
  300. $data = array_merge($data, $extend);
  301. Db::startTrans();
  302. try {
  303. $this->model = User::create($data);
  304. $this->token = Random::uuid();
  305. Token::set($this->token, 'user', $this->model->id, $this->keeptime);
  306. Event::trigger('userRegisterSuccessed', $this->model);
  307. Db::commit();
  308. } catch (PDOException|Exception $e) {
  309. $this->setError($e->getMessage());
  310. Db::rollback();
  311. return false;
  312. }
  313. return true;
  314. }
  315. /**
  316. * 直接登录会员账号
  317. * @param int $userId 用户ID
  318. * @return bool
  319. * @throws DataNotFoundException
  320. * @throws DbException
  321. * @throws ModelNotFoundException
  322. */
  323. public function direct(int $userId): bool
  324. {
  325. $this->model = User::find($userId);
  326. if (!$this->model) return false;
  327. if (Config::get('buildadmin.user_sso')) {
  328. Token::clear('user', $this->model->id);
  329. Token::clear('user-refresh', $this->model->id);
  330. }
  331. return $this->loginSuccessful();
  332. }
  333. /**
  334. * 检查旧密码是否正确
  335. * @param $password
  336. * @return bool
  337. */
  338. public function checkPassword($password): bool
  339. {
  340. if ($this->model->password != encrypt_password($password, $this->model->salt)) {
  341. return false;
  342. } else {
  343. return true;
  344. }
  345. }
  346. /**
  347. * 登录成功
  348. * @return bool
  349. */
  350. public function loginSuccessful(): bool
  351. {
  352. if (!$this->model) {
  353. return false;
  354. }
  355. Db::startTrans();
  356. try {
  357. $this->model->loginfailure = 0;
  358. $this->model->lastlogintime = time();
  359. $this->model->lastloginip = request()->ip();
  360. $this->model->save();
  361. $this->logined = true;
  362. if (!$this->token) {
  363. $this->token = Random::uuid();
  364. Token::set($this->token, 'user', $this->model->id, $this->keeptime);
  365. }
  366. Db::commit();
  367. } catch (PDOException|Exception $e) {
  368. Db::rollback();
  369. $this->setError($e->getMessage());
  370. return false;
  371. }
  372. return true;
  373. }
  374. /**
  375. * 登录失败
  376. * @return bool
  377. */
  378. public function loginFailed(): bool
  379. {
  380. if (!$this->model) {
  381. return false;
  382. }
  383. Db::startTrans();
  384. try {
  385. $this->model->loginfailure++;
  386. $this->model->lastlogintime = time();
  387. $this->model->lastloginip = request()->ip();
  388. $this->model->save();
  389. $this->token = '';
  390. $this->model = null;
  391. $this->logined = false;
  392. Db::commit();
  393. } catch (PDOException|Exception $e) {
  394. Db::rollback();
  395. $this->setError($e->getMessage());
  396. return false;
  397. }
  398. return true;
  399. }
  400. /**
  401. * 退出登录
  402. * @return bool
  403. */
  404. public function logout(): bool
  405. {
  406. if (!$this->logined) {
  407. $this->setError('You are not logged in');
  408. return false;
  409. }
  410. $this->logined = false;
  411. Token::delete($this->token);
  412. $this->token = '';
  413. return true;
  414. }
  415. /**
  416. * 是否登录
  417. * @return bool
  418. */
  419. public function isLogin(): bool
  420. {
  421. return $this->logined;
  422. }
  423. /**
  424. * 获取会员模型
  425. * @return User
  426. */
  427. public function getUser(): User
  428. {
  429. return $this->model;
  430. }
  431. /**
  432. * 获取会员Token
  433. * @return string
  434. */
  435. public function getToken(): string
  436. {
  437. return $this->token;
  438. }
  439. /**
  440. * 设置刷新Token
  441. * @param int $keeptime
  442. */
  443. public function setRefreshToken(int $keeptime = 0)
  444. {
  445. $this->refreshToken = Random::uuid();
  446. Token::set($this->refreshToken, 'user-refresh', $this->model->id, $keeptime);
  447. }
  448. /**
  449. * 获取会员刷新Token
  450. * @return string
  451. */
  452. public function getRefreshToken(): string
  453. {
  454. return $this->refreshToken;
  455. }
  456. /**
  457. * 获取会员信息 - 只输出允许输出的字段
  458. * @return array
  459. */
  460. public function getUserInfo(): array
  461. {
  462. if (!$this->model) {
  463. return [];
  464. }
  465. $info = $this->model->toArray();
  466. $info = array_intersect_key($info, array_flip($this->getAllowFields()));
  467. $info['token'] = $this->getToken();
  468. $info['refreshToken'] = $this->getRefreshToken();
  469. return $info;
  470. }
  471. /**
  472. * 获取允许输出字段
  473. * @return string[]
  474. */
  475. public function getAllowFields(): array
  476. {
  477. return $this->allowFields;
  478. }
  479. /**
  480. * 设置允许输出字段
  481. * @param $fields
  482. */
  483. public function setAllowFields($fields)
  484. {
  485. $this->allowFields = $fields;
  486. }
  487. /**
  488. * 设置Token有效期
  489. * @param int $keeptime
  490. */
  491. public function setKeeptime(int $keeptime = 0)
  492. {
  493. $this->keeptime = $keeptime;
  494. }
  495. public function check(string $name, int $uid = 0, string $relation = 'or', string $mode = 'url'): bool
  496. {
  497. return parent::check($name, $uid ?: $this->id, $relation, $mode);
  498. }
  499. public function getRuleList(int $uid = 0): array
  500. {
  501. return parent::getRuleList($uid ?: $this->id);
  502. }
  503. public function getRuleIds(int $uid = 0): array
  504. {
  505. return parent::getRuleIds($uid ?: $this->id);
  506. }
  507. public function getMenus(int $uid = 0): array
  508. {
  509. return parent::getMenus($uid ?: $this->id);
  510. }
  511. public function isSuperUser(): bool
  512. {
  513. return in_array('*', $this->getRuleIds());
  514. }
  515. /**
  516. * 设置错误消息
  517. * @param $error
  518. * @return $this
  519. */
  520. public function setError($error): Auth
  521. {
  522. $this->error = $error;
  523. return $this;
  524. }
  525. /**
  526. * 获取错误消息
  527. * @return float|int|string
  528. */
  529. public function getError()
  530. {
  531. return $this->error ? __($this->error) : '';
  532. }
  533. /**
  534. * @param string $nickname 昵称
  535. * @param string $mobile 联系方式
  536. * @param string $email 邮箱
  537. * @param string $avatar 头像
  538. * @param string $gender 性别
  539. * @param string $birthday 生日
  540. * @return bool
  541. */
  542. public function updateUser(string $nickname,string $mobile, string $email,string $avatar,string $gender,string $birthday):bool{
  543. if (!$this->model) {
  544. return false;
  545. }
  546. Db::startTrans();
  547. try {
  548. if($nickname!=='') $this->model->nickname = $nickname;
  549. if($mobile!=='') $this->model->mobile = $mobile;
  550. if($email!=='') $this->model->email = $email;
  551. if($avatar!=='') $this->model->avatar = $avatar;
  552. if($gender!=='') $this->model->gender = $gender;
  553. if($birthday!=='') $this->model->birthday = $birthday;
  554. $this->model->updatetime = time();
  555. $this->model->save();
  556. Db::commit();
  557. } catch (PDOException|Exception $e) {
  558. Db::rollback();
  559. $this->setError($e->getMessage());
  560. return false;
  561. }
  562. return true;
  563. }
  564. }