Auth.php 18 KB

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