Auth.php 17 KB

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