Auth.php 16 KB

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