Auth.php 20 KB

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