Auth.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. <?php
  2. namespace app\common\library;
  3. use app\admin\controller\user\User;
  4. use app\common\model\Users;
  5. use app\common\model\UserRule;
  6. use app\common\model\UsersPath;
  7. use fast\Random;
  8. use think\Config;
  9. use think\Db;
  10. use think\Exception;
  11. use think\Hook;
  12. use think\Request;
  13. use think\Validate;
  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'];
  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 Users
  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 = Users::get($user_id);
  94. if (!$user) {
  95. $this->setError('Account not exist');
  96. return false;
  97. }
  98. if ($user['is_lock'] == 1) {
  99. $this->setError('Account is locked');
  100. return false;
  101. }
  102. //已删除
  103. if ($user['is_delete'] == 1) {
  104. $this->setError('账号不存在');
  105. return false;
  106. }
  107. $this->_user = $user;
  108. $this->_logined = true;
  109. $this->_token = $token;
  110. //初始化成功的事件
  111. Hook::listen("user_init_successed", $this->_user);
  112. return true;
  113. } else {
  114. $this->setError('You are not logged in');
  115. return false;
  116. }
  117. }
  118. /**
  119. * 注册用户
  120. *
  121. * @param string $username 用户名
  122. * @param string $password 密码
  123. * @param string $email 邮箱
  124. * @param string $mobile 手机号
  125. * @param array $extend 扩展参数
  126. * @return boolean
  127. */
  128. public function register($code, $mobile, $password, $invitation_code)
  129. {
  130. // 检测用户名、昵称、邮箱、手机号是否存在
  131. // if (User::getByUsername($username)) {
  132. // $this->setError('Username already exist');
  133. // return false;
  134. // }
  135. // if (User::getByNickname($username)) {
  136. // $this->setError('Nickname already exist');
  137. // return false;
  138. // }
  139. // if ($email && User::getByEmail($email)) {
  140. // $this->setError('Email already exist');
  141. // return false;
  142. // }
  143. if ($mobile && Users::getByCodeAndMobile($code, $mobile)) {
  144. $this->setError('Mobile already exist');
  145. return false;
  146. }
  147. $parent_info = Users::getByInvitationCode($invitation_code);
  148. if(empty($parent_info)){
  149. $this->setError('邀请码有误');
  150. return false;
  151. }
  152. $ip = request()->ip();
  153. $time = time();
  154. $user_data = [
  155. //'username' => $username,
  156. //'email' => $email,
  157. 'mobile' => $mobile,
  158. 'code' => $code,
  159. 'login_pwd'=> $password,
  160. 'parent_id'=> $parent_info['id'],
  161. 'agent_id' => $parent_info['agent_id'],
  162. 'invitation_code' => (new Users)->generateInviteCode(),
  163. 'user_type'=> 1,//真人
  164. ];
  165. if($parent_info['is_agent']){
  166. $user_data['agent_id'] = $parent_info['id'];
  167. }
  168. $user_data = array_merge($user_data, [
  169. 'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $mobile) ? substr_replace($mobile, '****', 3, 4) : $mobile,
  170. 'salt' => Random::alnum(),
  171. 'join_time' => $time,
  172. 'login_ip' => $ip,
  173. 'login_time'=> $time,
  174. ]);
  175. $user_data['login_pwd'] = $this->getEncryptPassword($password, $user_data['salt']);
  176. //$params = array_merge($params, $extend);
  177. //账号注册时需要开启事务,避免出现垃圾数据
  178. Db::startTrans();
  179. try {
  180. $user = Users::create($user_data, true);
  181. $this->_user = Users::get($user->id);
  182. // 创建网体
  183. (new UsersPath())->createPath($user->id, $parent_info['id']);
  184. //上级人数+1
  185. (new Users())->where('id', $parent_info['id'])->setInc('team_num');
  186. //设置Token
  187. $this->_token = Random::uuid();
  188. Token::set($this->_token, $user->id, $this->keeptime);
  189. //设置登录状态
  190. $this->_logined = true;
  191. //注册成功的事件
  192. Hook::listen("user_register_successed", $this->_user, $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($code, $account, $password)
  209. {
  210. //$field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  211. $user = Users::where('mobile', $account)
  212. ->where('is_delete',0)
  213. ->find();
  214. if (!$user) {
  215. $this->setError('Account is incorrect');
  216. return false;
  217. }
  218. if ($user->is_lock == 1) {
  219. $this->setError('Account is locked');
  220. return false;
  221. }
  222. if ($user->login_pwd != $this->getEncryptPassword($password, $user->salt)) {
  223. $this->setError('Password is incorrect');
  224. return false;
  225. }
  226. //直接登录会员
  227. return $this->direct($user->id);
  228. }
  229. /**
  230. * 退出
  231. *
  232. * @return boolean
  233. */
  234. public function logout()
  235. {
  236. if (!$this->_logined) {
  237. $this->setError('You are not logged in');
  238. return false;
  239. }
  240. //设置登录标识
  241. $this->_logined = false;
  242. //删除Token
  243. Token::delete($this->_token);
  244. //退出成功的事件
  245. Hook::listen("user_logout_successed", $this->_user);
  246. return true;
  247. }
  248. /**
  249. * 修改密码
  250. * @param string $newpassword 新密码
  251. * @param string $oldpassword 旧密码
  252. * @param bool $ignoreoldpassword 忽略旧密码
  253. * @return boolean
  254. */
  255. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  256. {
  257. if (!$this->_logined) {
  258. $this->setError('You are not logged in');
  259. return false;
  260. }
  261. //判断旧密码是否正确
  262. if ($this->_user->login_pwd == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  263. Db::startTrans();
  264. try {
  265. $salt = Random::alnum();
  266. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  267. $this->_user->save(['login_pwd' => $newpassword, 'salt' => $salt]);
  268. Token::delete($this->_token);
  269. //修改密码成功的事件
  270. Hook::listen("user_changepwd_successed", $this->_user);
  271. Db::commit();
  272. } catch (Exception $e) {
  273. Db::rollback();
  274. $this->setError($e->getMessage());
  275. return false;
  276. }
  277. return true;
  278. } else {
  279. $this->setError('Password is incorrect');
  280. return false;
  281. }
  282. }
  283. /**
  284. * 直接登录账号
  285. * @param int $user_id
  286. * @return boolean
  287. */
  288. public function direct($user_id)
  289. {
  290. $user = Users::get($user_id);
  291. if ($user) {
  292. Db::startTrans();
  293. try {
  294. $ip = request()->ip();
  295. $time = time();
  296. //判断连续登录和最大连续登录
  297. // if ($user->logintime < \fast\Date::unixtime('day')) {
  298. // $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  299. // $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  300. // }
  301. //$user->prevtime = $user->logintime;
  302. //记录本次登录的IP和时间
  303. $user->login_ip = $ip;
  304. $user->login_time = $time;
  305. //重置登录失败次数
  306. //$user->loginfailure = 0;
  307. $user->save();
  308. $this->_user = $user;
  309. $this->_token = Random::uuid();
  310. Token::set($this->_token, $user->id, $this->keeptime);
  311. $this->_logined = true;
  312. //登录成功的事件
  313. Hook::listen("user_login_successed", $this->_user);
  314. Db::commit();
  315. } catch (Exception $e) {
  316. Db::rollback();
  317. $this->setError($e->getMessage());
  318. return false;
  319. }
  320. return true;
  321. } else {
  322. return false;
  323. }
  324. }
  325. /**
  326. * 检测是否是否有对应权限
  327. * @param string $path 控制器/方法
  328. * @param string $module 模块 默认为当前模块
  329. * @return boolean
  330. */
  331. public function check($path = null, $module = null)
  332. {
  333. if (!$this->_logined) {
  334. return false;
  335. }
  336. $ruleList = $this->getRuleList();
  337. $rules = [];
  338. foreach ($ruleList as $k => $v) {
  339. $rules[] = $v['name'];
  340. }
  341. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  342. $url = strtolower(str_replace('.', '/', $url));
  343. return in_array($url, $rules);
  344. }
  345. /**
  346. * 判断是否登录
  347. * @return boolean
  348. */
  349. public function isLogin()
  350. {
  351. if ($this->_logined) {
  352. return true;
  353. }
  354. return false;
  355. }
  356. /**
  357. * 获取当前Token
  358. * @return string
  359. */
  360. public function getToken()
  361. {
  362. return $this->_token;
  363. }
  364. /**
  365. * 获取会员基本信息
  366. */
  367. public function getUserinfo()
  368. {
  369. $data = $this->_user->toArray();
  370. $allowFields = $this->getAllowFields();
  371. $userinfo = array_intersect_key($data, array_flip($allowFields));
  372. $userinfo = array_merge($userinfo, Token::get($this->_token));
  373. return $userinfo;
  374. }
  375. /**
  376. * 获取会员组别规则列表
  377. * @return array|bool|\PDOStatement|string|\think\Collection
  378. */
  379. public function getRuleList()
  380. {
  381. if ($this->rules) {
  382. return $this->rules;
  383. }
  384. $group = $this->_user->group;
  385. if (!$group) {
  386. return [];
  387. }
  388. $rules = explode(',', $group->rules);
  389. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  390. return $this->rules;
  391. }
  392. /**
  393. * 获取当前请求的URI
  394. * @return string
  395. */
  396. public function getRequestUri()
  397. {
  398. return $this->requestUri;
  399. }
  400. /**
  401. * 设置当前请求的URI
  402. * @param string $uri
  403. */
  404. public function setRequestUri($uri)
  405. {
  406. $this->requestUri = $uri;
  407. }
  408. /**
  409. * 获取允许输出的字段
  410. * @return array
  411. */
  412. public function getAllowFields()
  413. {
  414. return $this->allowFields;
  415. }
  416. /**
  417. * 设置允许输出的字段
  418. * @param array $fields
  419. */
  420. public function setAllowFields($fields)
  421. {
  422. $this->allowFields = $fields;
  423. }
  424. /**
  425. * 删除一个指定会员
  426. * @param int $user_id 会员ID
  427. * @return boolean
  428. */
  429. public function delete($user_id)
  430. {
  431. $user = Users::get($user_id);
  432. if (!$user) {
  433. return false;
  434. }
  435. Db::startTrans();
  436. try {
  437. // 删除会员
  438. Users::destroy($user_id);
  439. // 删除会员指定的所有Token
  440. Token::clear($user_id);
  441. Hook::listen("user_delete_successed", $user);
  442. Db::commit();
  443. } catch (Exception $e) {
  444. Db::rollback();
  445. $this->setError($e->getMessage());
  446. return false;
  447. }
  448. return true;
  449. }
  450. /**
  451. * 获取密码加密后的字符串
  452. * @param string $password 密码
  453. * @param string $salt 密码盐
  454. * @return string
  455. */
  456. public function getEncryptPassword($password, $salt = '')
  457. {
  458. return md5(md5($password) . $salt);
  459. }
  460. /**
  461. * 检测当前控制器和方法是否匹配传递的数组
  462. *
  463. * @param array $arr 需要验证权限的数组
  464. * @return boolean
  465. */
  466. public function match($arr = [])
  467. {
  468. $request = Request::instance();
  469. $arr = is_array($arr) ? $arr : explode(',', $arr);
  470. if (!$arr) {
  471. return false;
  472. }
  473. $arr = array_map('strtolower', $arr);
  474. // 是否存在
  475. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  476. return true;
  477. }
  478. // 没找到匹配
  479. return false;
  480. }
  481. /**+
  482. * 设置会话有效时间
  483. * @param int $keeptime 默认为永久
  484. */
  485. public function keeptime($keeptime = 0)
  486. {
  487. $this->keeptime = $keeptime;
  488. }
  489. /**
  490. * 渲染用户数据
  491. * @param array $datalist 二维数组
  492. * @param mixed $fields 加载的字段列表
  493. * @param string $fieldkey 渲染的字段
  494. * @param string $renderkey 结果字段
  495. * @return array
  496. */
  497. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  498. {
  499. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  500. $ids = [];
  501. foreach ($datalist as $k => $v) {
  502. if (!isset($v[$fieldkey])) {
  503. continue;
  504. }
  505. $ids[] = $v[$fieldkey];
  506. }
  507. $list = [];
  508. if ($ids) {
  509. if (!in_array('id', $fields)) {
  510. $fields[] = 'id';
  511. }
  512. $ids = array_unique($ids);
  513. $selectlist = Users::where('id', 'in', $ids)->column($fields);
  514. foreach ($selectlist as $k => $v) {
  515. $list[$v['id']] = $v;
  516. }
  517. }
  518. foreach ($datalist as $k => &$v) {
  519. $v[$renderkey] = $list[$v[$fieldkey]] ?? null;
  520. }
  521. unset($v);
  522. return $datalist;
  523. }
  524. /**
  525. * 设置错误信息
  526. *
  527. * @param string $error 错误信息
  528. * @return Auth
  529. */
  530. public function setError($error)
  531. {
  532. $this->_error = $error;
  533. return $this;
  534. }
  535. /**
  536. * 获取错误信息
  537. * @return string
  538. */
  539. public function getError()
  540. {
  541. return $this->_error ? __($this->_error) : '';
  542. }
  543. }