Auth.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. <?php
  2. namespace app\common\library;
  3. use app\common\model\User;
  4. use app\common\model\UserRule;
  5. use fast\Random;
  6. use think\Config;
  7. use think\Db;
  8. use think\Exception;
  9. use think\Hook;
  10. use think\Request;
  11. use think\Validate;
  12. use app\common\Enum\StatusEnum;
  13. use app\common\Service\ShopConfigService;
  14. class Auth
  15. {
  16. protected static $instance = null;
  17. protected $_error = '';
  18. protected $_logined = false;
  19. protected $_user = null;
  20. protected $_token = '';
  21. //Token默认有效时长
  22. protected $keeptime = 2592000;
  23. protected $requestUri = '';
  24. protected $rules = [];
  25. //默认配置
  26. protected $config = [];
  27. protected $options = [];
  28. protected $allowFields = ['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'level', 'bio', 'balance', 'money', 'gender'];
  29. public function __construct($options = [])
  30. {
  31. if ($config = Config::get('user')) {
  32. $this->config = array_merge($this->config, $config);
  33. }
  34. $this->options = array_merge($this->config, $options);
  35. }
  36. /**
  37. *
  38. * @param array $options 参数
  39. * @return Auth
  40. */
  41. public static function instance($options = [])
  42. {
  43. if (is_null(self::$instance)) {
  44. self::$instance = new static($options);
  45. }
  46. return self::$instance;
  47. }
  48. /**
  49. * 获取User模型
  50. * @return User
  51. */
  52. public function getUser()
  53. {
  54. return $this->_user;
  55. }
  56. /**
  57. * 兼容调用user模型的属性
  58. *
  59. * @param string $name
  60. * @return mixed
  61. */
  62. public function __get($name)
  63. {
  64. return $this->_user ? $this->_user->$name : null;
  65. }
  66. /**
  67. * 兼容调用user模型的属性
  68. */
  69. public function __isset($name)
  70. {
  71. return isset($this->_user) ? isset($this->_user->$name) : false;
  72. }
  73. /**
  74. * 根据Token初始化
  75. *
  76. * @param string $token Token
  77. * @return boolean
  78. */
  79. public function init($token)
  80. {
  81. if ($this->_logined) {
  82. return true;
  83. }
  84. if ($this->_error) {
  85. return false;
  86. }
  87. $data = Token::get($token);
  88. if (!$data) {
  89. return false;
  90. }
  91. $user_id = intval($data['user_id']);
  92. if ($user_id > 0) {
  93. $user = User::get($user_id);
  94. if (!$user) {
  95. $this->setError('Account not exist');
  96. return false;
  97. }
  98. if ($user['status'] != StatusEnum::ENABLED) {
  99. $this->setError('Account is locked');
  100. return false;
  101. }
  102. $this->_user = $user;
  103. $this->_logined = true;
  104. $this->_token = $token;
  105. //初始化成功的事件
  106. Hook::listen("user_init_successed", $this->_user);
  107. return true;
  108. } else {
  109. $this->setError('You are not logged in');
  110. return false;
  111. }
  112. }
  113. /**
  114. * 生成随机字符串
  115. * @param int $len 字符串长度
  116. * @return string
  117. */
  118. public function GetRandStr($len) {
  119. $chars = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a", "b", "c","d", "e", "f", "g", "h", "i", "j", "k","l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v","w", "x", "y", "z","0", "1", "2","3", "4", "5", "6", "7", "8", "9");
  120. $charsLen = count($chars) - 1;
  121. shuffle($chars);
  122. $output = "";
  123. for ($i=0; $i<$len; $i++){
  124. $output .= $chars[mt_rand(0, $charsLen)];
  125. }
  126. return $output;
  127. }
  128. /**
  129. * 生成随机用户名
  130. * @param string $prefix 前缀
  131. * @param int $length 随机部分长度
  132. * @return string
  133. */
  134. public function generateUniqueUsername($prefix = 'user', $length = 8)
  135. {
  136. $randomPart = $this->GetRandStr($length);
  137. return $prefix .'_' . $randomPart;
  138. }
  139. /**
  140. * 注册用户
  141. *
  142. * @param string $username 用户名
  143. * @param string $password 密码
  144. * @param string $email 邮箱
  145. * @param string $mobile 手机号
  146. * @param array $extend 扩展参数
  147. * @return boolean
  148. */
  149. public function register($username, $password, $email = '', $mobile = '', $extend = [])
  150. {
  151. // 检测用户名、昵称、邮箱、手机号是否存在
  152. if (User::getByUsername($username)) {
  153. $this->setError('Username already exist');
  154. return false;
  155. }
  156. if (User::getByNickname($username)) {
  157. $this->setError('Nickname already exist');
  158. return false;
  159. }
  160. if ($email && User::getByEmail($email)) {
  161. $this->setError('Email already exist');
  162. return false;
  163. }
  164. if ($mobile && User::getByMobile($mobile)) {
  165. $this->setError('Mobile already exist');
  166. return false;
  167. }
  168. $ip = request()->ip();
  169. $time = time();
  170. $defaultavatar = ShopConfigService::getConfigs('shop.basic.default_user_avator',false) ?? "";
  171. //$params['avatar'] = $defaultavatar;
  172. $data = [
  173. 'username' => $username,
  174. 'password' => $password,
  175. 'email' => $email,
  176. 'mobile' => $mobile,
  177. 'level' => 1,
  178. 'score' => 0,
  179. 'avatar' => $defaultavatar,
  180. ];
  181. $params = array_merge($data, [
  182. 'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
  183. 'salt' => Random::alnum(),
  184. 'jointime' => $time,
  185. 'joinip' => $ip,
  186. 'logintime' => $time,
  187. 'loginip' => $ip,
  188. 'prevtime' => $time,
  189. 'status' => StatusEnum::ENABLED
  190. ]);
  191. //注册默认头像
  192. //查询配置
  193. $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  194. $params = array_merge($params, $extend);
  195. //账号注册时需要开启事务,避免出现垃圾数据
  196. Db::startTrans();
  197. try {
  198. $user = User::create($params, true);
  199. $this->_user = User::get($user->id);
  200. //设置Token
  201. $this->_token = Random::uuid();
  202. Token::set($this->_token, $user->id, $this->keeptime);
  203. //设置登录状态
  204. $this->_logined = true;
  205. //注册成功的事件
  206. Hook::listen("user_register_successed", $this->_user, $data);
  207. Db::commit();
  208. } catch (Exception $e) {
  209. $this->setError($e->getMessage());
  210. Db::rollback();
  211. return false;
  212. }
  213. return true;
  214. }
  215. /**
  216. * 用户登录
  217. *
  218. * @param string $account 账号,用户名、邮箱、手机号
  219. * @param string $password 密码
  220. * @return boolean
  221. */
  222. public function login($account, $password)
  223. {
  224. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  225. $user = User::get([$field => $account]);
  226. if (!$user) {
  227. $this->setError('Account is incorrect');
  228. return false;
  229. }
  230. if ($user->status != StatusEnum::ENABLED) {
  231. $this->setError('Account is locked');
  232. return false;
  233. }
  234. if ($user->loginfailure >= 10 && time() - $user->loginfailuretime < 86400) {
  235. $this->setError('Please try again after 1 day');
  236. return false;
  237. }
  238. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  239. $user->save(['loginfailure' => $user->loginfailure + 1, 'loginfailuretime' => time()]);
  240. $this->setError('Password is incorrect');
  241. return false;
  242. }
  243. //直接登录会员
  244. return $this->direct($user->id);
  245. }
  246. /**
  247. * 退出
  248. *
  249. * @return boolean
  250. */
  251. public function logout()
  252. {
  253. if (!$this->_logined) {
  254. $this->setError('You are not logged in');
  255. return false;
  256. }
  257. //设置登录标识
  258. $this->_logined = false;
  259. //删除Token
  260. Token::delete($this->_token);
  261. //退出成功的事件
  262. Hook::listen("user_logout_successed", $this->_user);
  263. return true;
  264. }
  265. /**
  266. * 修改密码
  267. * @param string $newpassword 新密码
  268. * @param string $oldpassword 旧密码
  269. * @param bool $ignoreoldpassword 忽略旧密码
  270. * @return boolean
  271. */
  272. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  273. {
  274. if (!$this->_logined) {
  275. $this->setError('You are not logged in');
  276. return false;
  277. }
  278. //判断旧密码是否正确
  279. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  280. Db::startTrans();
  281. try {
  282. $salt = Random::alnum();
  283. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  284. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  285. Token::delete($this->_token);
  286. //修改密码成功的事件
  287. Hook::listen("user_changepwd_successed", $this->_user);
  288. Db::commit();
  289. } catch (Exception $e) {
  290. Db::rollback();
  291. $this->setError($e->getMessage());
  292. return false;
  293. }
  294. return true;
  295. } else {
  296. $this->setError('Password is incorrect');
  297. return false;
  298. }
  299. }
  300. /**
  301. * 直接登录账号
  302. * @param int $user_id
  303. * @return boolean
  304. */
  305. public function direct($user_id)
  306. {
  307. $user = User::get($user_id);
  308. if ($user) {
  309. Db::startTrans();
  310. try {
  311. $ip = request()->ip();
  312. $time = time();
  313. //判断连续登录和最大连续登录
  314. if ($user->logintime < \fast\Date::unixtime('day')) {
  315. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  316. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  317. }
  318. $user->prevtime = $user->logintime;
  319. //记录本次登录的IP和时间
  320. $user->loginip = $ip;
  321. $user->logintime = $time;
  322. //重置登录失败次数
  323. $user->loginfailure = 0;
  324. $user->save();
  325. $this->_user = $user;
  326. $this->_token = Random::uuid();
  327. Token::set($this->_token, $user->id, $this->keeptime);
  328. $this->_logined = true;
  329. //登录成功的事件
  330. Hook::listen("user_login_successed", $this->_user);
  331. Db::commit();
  332. } catch (Exception $e) {
  333. Db::rollback();
  334. $this->setError($e->getMessage());
  335. return false;
  336. }
  337. return true;
  338. } else {
  339. return false;
  340. }
  341. }
  342. /**
  343. * 检测是否是否有对应权限
  344. * @param string $path 控制器/方法
  345. * @param string $module 模块 默认为当前模块
  346. * @return boolean
  347. */
  348. public function check($path = null, $module = null)
  349. {
  350. if (!$this->_logined) {
  351. return false;
  352. }
  353. $ruleList = $this->getRuleList();
  354. $rules = [];
  355. foreach ($ruleList as $k => $v) {
  356. $rules[] = $v['name'];
  357. }
  358. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  359. $url = strtolower(str_replace('.', '/', $url));
  360. return in_array($url, $rules);
  361. }
  362. /**
  363. * 判断是否登录
  364. * @return boolean
  365. */
  366. public function isLogin()
  367. {
  368. if ($this->_logined) {
  369. return true;
  370. }
  371. return false;
  372. }
  373. /**
  374. * 获取当前Token
  375. * @return string
  376. */
  377. public function getToken()
  378. {
  379. return $this->_token;
  380. }
  381. /**
  382. * 获取会员基本信息
  383. */
  384. public function getUserinfo()
  385. {
  386. $data = $this->_user->toArray();
  387. $allowFields = $this->getAllowFields();
  388. $userinfo = array_intersect_key($data, array_flip($allowFields));
  389. $userinfo = array_merge($userinfo, Token::get($this->_token));
  390. return $userinfo;
  391. }
  392. /**
  393. * 获取会员组别规则列表
  394. * @return array|bool|\PDOStatement|string|\think\Collection
  395. */
  396. public function getRuleList()
  397. {
  398. if ($this->rules) {
  399. return $this->rules;
  400. }
  401. $group = $this->_user->group;
  402. if (!$group) {
  403. return [];
  404. }
  405. $rules = explode(',', $group->rules);
  406. $this->rules = UserRule::where('status',StatusEnum::ENABLED)->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  407. return $this->rules;
  408. }
  409. /**
  410. * 获取当前请求的URI
  411. * @return string
  412. */
  413. public function getRequestUri()
  414. {
  415. return $this->requestUri;
  416. }
  417. /**
  418. * 设置当前请求的URI
  419. * @param string $uri
  420. */
  421. public function setRequestUri($uri)
  422. {
  423. $this->requestUri = $uri;
  424. }
  425. /**
  426. * 获取允许输出的字段
  427. * @return array
  428. */
  429. public function getAllowFields()
  430. {
  431. return $this->allowFields;
  432. }
  433. /**
  434. * 设置允许输出的字段
  435. * @param array $fields
  436. */
  437. public function setAllowFields($fields)
  438. {
  439. $this->allowFields = $fields;
  440. }
  441. /**
  442. * 删除一个指定会员
  443. * @param int $user_id 会员ID
  444. * @return boolean
  445. */
  446. public function delete($user_id)
  447. {
  448. $user = User::get($user_id);
  449. if (!$user) {
  450. return false;
  451. }
  452. Db::startTrans();
  453. try {
  454. // 删除会员
  455. User::destroy($user_id);
  456. // 删除会员指定的所有Token
  457. Token::clear($user_id);
  458. Hook::listen("user_delete_successed", $user);
  459. Db::commit();
  460. } catch (Exception $e) {
  461. Db::rollback();
  462. $this->setError($e->getMessage());
  463. return false;
  464. }
  465. return true;
  466. }
  467. /**
  468. * 获取密码加密后的字符串
  469. * @param string $password 密码
  470. * @param string $salt 密码盐
  471. * @return string
  472. */
  473. public function getEncryptPassword($password, $salt = '')
  474. {
  475. return md5(md5($password) . $salt);
  476. }
  477. /**
  478. * 检测当前控制器和方法是否匹配传递的数组
  479. *
  480. * @param array $arr 需要验证权限的数组
  481. * @return boolean
  482. */
  483. public function match($arr = [])
  484. {
  485. $request = Request::instance();
  486. $arr = is_array($arr) ? $arr : explode(',', $arr);
  487. if (!$arr) {
  488. return false;
  489. }
  490. $arr = array_map('strtolower', $arr);
  491. // 是否存在
  492. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  493. return true;
  494. }
  495. // 没找到匹配
  496. return false;
  497. }
  498. /**
  499. * 设置会话有效时间
  500. * @param int $keeptime 默认为永久
  501. */
  502. public function keeptime($keeptime = 0)
  503. {
  504. $this->keeptime = $keeptime;
  505. }
  506. /**
  507. * 渲染用户数据
  508. * @param array $datalist 二维数组
  509. * @param mixed $fields 加载的字段列表
  510. * @param string $fieldkey 渲染的字段
  511. * @param string $renderkey 结果字段
  512. * @return array
  513. */
  514. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  515. {
  516. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  517. $ids = [];
  518. foreach ($datalist as $k => $v) {
  519. if (!isset($v[$fieldkey])) {
  520. continue;
  521. }
  522. $ids[] = $v[$fieldkey];
  523. }
  524. $list = [];
  525. if ($ids) {
  526. if (!in_array('id', $fields)) {
  527. $fields[] = 'id';
  528. }
  529. $ids = array_unique($ids);
  530. $selectlist = User::where('id', 'in', $ids)->column($fields);
  531. foreach ($selectlist as $k => $v) {
  532. $list[$v['id']] = $v;
  533. }
  534. }
  535. foreach ($datalist as $k => &$v) {
  536. $v[$renderkey] = $list[$v[$fieldkey]] ?? null;
  537. }
  538. unset($v);
  539. return $datalist;
  540. }
  541. /**
  542. * 设置错误信息
  543. *
  544. * @param string $error 错误信息
  545. * @return Auth
  546. */
  547. public function setError($error)
  548. {
  549. $this->_error = $error;
  550. return $this;
  551. }
  552. /**
  553. * 获取错误信息
  554. * @return string
  555. */
  556. public function getError()
  557. {
  558. return $this->_error ? __($this->_error) : '';
  559. }
  560. }