Auth.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. * 直接登录会员账号
  236. * @param int $userId 用户ID
  237. * @return bool
  238. * @throws DataNotFoundException
  239. * @throws DbException
  240. * @throws ModelNotFoundException
  241. */
  242. public function direct(int $userId): bool
  243. {
  244. $this->model = User::find($userId);
  245. if (!$this->model) return false;
  246. if (Config::get('buildadmin.user_sso')) {
  247. Token::clear('user', $this->model->id);
  248. Token::clear('user-refresh', $this->model->id);
  249. }
  250. return $this->loginSuccessful();
  251. }
  252. /**
  253. * 检查旧密码是否正确
  254. * @param $password
  255. * @return bool
  256. */
  257. public function checkPassword($password): bool
  258. {
  259. if ($this->model->password != encrypt_password($password, $this->model->salt)) {
  260. return false;
  261. } else {
  262. return true;
  263. }
  264. }
  265. /**
  266. * 登录成功
  267. * @return bool
  268. */
  269. public function loginSuccessful(): bool
  270. {
  271. if (!$this->model) {
  272. return false;
  273. }
  274. Db::startTrans();
  275. try {
  276. $this->model->loginfailure = 0;
  277. $this->model->lastlogintime = time();
  278. $this->model->lastloginip = request()->ip();
  279. $this->model->save();
  280. $this->logined = true;
  281. if (!$this->token) {
  282. $this->token = Random::uuid();
  283. Token::set($this->token, 'user', $this->model->id, $this->keeptime);
  284. }
  285. Db::commit();
  286. } catch (PDOException|Exception $e) {
  287. Db::rollback();
  288. $this->setError($e->getMessage());
  289. return false;
  290. }
  291. return true;
  292. }
  293. /**
  294. * 登录失败
  295. * @return bool
  296. */
  297. public function loginFailed(): bool
  298. {
  299. if (!$this->model) {
  300. return false;
  301. }
  302. Db::startTrans();
  303. try {
  304. $this->model->loginfailure++;
  305. $this->model->lastlogintime = time();
  306. $this->model->lastloginip = request()->ip();
  307. $this->model->save();
  308. $this->token = '';
  309. $this->model = null;
  310. $this->logined = false;
  311. Db::commit();
  312. } catch (PDOException|Exception $e) {
  313. Db::rollback();
  314. $this->setError($e->getMessage());
  315. return false;
  316. }
  317. return true;
  318. }
  319. /**
  320. * 退出登录
  321. * @return bool
  322. */
  323. public function logout(): bool
  324. {
  325. if (!$this->logined) {
  326. $this->setError('You are not logged in');
  327. return false;
  328. }
  329. $this->logined = false;
  330. Token::delete($this->token);
  331. $this->token = '';
  332. return true;
  333. }
  334. /**
  335. * 是否登录
  336. * @return bool
  337. */
  338. public function isLogin(): bool
  339. {
  340. return $this->logined;
  341. }
  342. /**
  343. * 获取会员模型
  344. * @return User
  345. */
  346. public function getUser(): User
  347. {
  348. return $this->model;
  349. }
  350. /**
  351. * 获取会员Token
  352. * @return string
  353. */
  354. public function getToken(): string
  355. {
  356. return $this->token;
  357. }
  358. /**
  359. * 设置刷新Token
  360. * @param int $keeptime
  361. */
  362. public function setRefreshToken(int $keeptime = 0)
  363. {
  364. $this->refreshToken = Random::uuid();
  365. Token::set($this->refreshToken, 'user-refresh', $this->model->id, $keeptime);
  366. }
  367. /**
  368. * 获取会员刷新Token
  369. * @return string
  370. */
  371. public function getRefreshToken(): string
  372. {
  373. return $this->refreshToken;
  374. }
  375. /**
  376. * 获取会员信息 - 只输出允许输出的字段
  377. * @return array
  378. */
  379. public function getUserInfo(): array
  380. {
  381. if (!$this->model) {
  382. return [];
  383. }
  384. $info = $this->model->toArray();
  385. $info = array_intersect_key($info, array_flip($this->getAllowFields()));
  386. $info['token'] = $this->getToken();
  387. $info['refreshToken'] = $this->getRefreshToken();
  388. return $info;
  389. }
  390. /**
  391. * 获取允许输出字段
  392. * @return string[]
  393. */
  394. public function getAllowFields(): array
  395. {
  396. return $this->allowFields;
  397. }
  398. /**
  399. * 设置允许输出字段
  400. * @param $fields
  401. */
  402. public function setAllowFields($fields)
  403. {
  404. $this->allowFields = $fields;
  405. }
  406. /**
  407. * 设置Token有效期
  408. * @param int $keeptime
  409. */
  410. public function setKeeptime(int $keeptime = 0)
  411. {
  412. $this->keeptime = $keeptime;
  413. }
  414. public function check(string $name, int $uid = 0, string $relation = 'or', string $mode = 'url'): bool
  415. {
  416. return parent::check($name, $uid ?: $this->id, $relation, $mode);
  417. }
  418. public function getRuleList(int $uid = 0): array
  419. {
  420. return parent::getRuleList($uid ?: $this->id);
  421. }
  422. public function getRuleIds(int $uid = 0): array
  423. {
  424. return parent::getRuleIds($uid ?: $this->id);
  425. }
  426. public function getMenus(int $uid = 0): array
  427. {
  428. return parent::getMenus($uid ?: $this->id);
  429. }
  430. public function isSuperUser(): bool
  431. {
  432. return in_array('*', $this->getRuleIds());
  433. }
  434. /**
  435. * 设置错误消息
  436. * @param $error
  437. * @return $this
  438. */
  439. public function setError($error): Auth
  440. {
  441. $this->error = $error;
  442. return $this;
  443. }
  444. /**
  445. * 获取错误消息
  446. * @return float|int|string
  447. */
  448. public function getError()
  449. {
  450. return $this->error ? __($this->error) : '';
  451. }
  452. }