Auth.php 17 KB

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