Auth.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. <?php
  2. namespace app\common\library;
  3. use app\common\model\User;
  4. use app\common\model\UserPower;
  5. use app\common\model\UserRule;
  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', 'u_id', 'username', 'nickname', 'mobile', 'pre_userid', 'has_info', 'is_auth', 'is_anchor', 'is_guild', 'guild_id', 'avatar', 'empirical', 'image', 'money', 'level', 'gender', 'age', 'jewel'];
  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 User
  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. * 根据Token初始化
  67. *
  68. * @param string $token Token
  69. * @return boolean
  70. */
  71. public function init($token)
  72. {
  73. if ($this->_logined) {
  74. return true;
  75. }
  76. if ($this->_error) {
  77. return false;
  78. }
  79. $data = Token::get($token);
  80. if (!$data) {
  81. return false;
  82. }
  83. $user_id = intval($data['user_id']);
  84. if ($user_id > 0) {
  85. $user = User::get($user_id);
  86. if (!$user) {
  87. $this->setError('Account not exist');
  88. return false;
  89. }
  90. if ($user['status'] != 'normal') {
  91. $this->setError('Account is locked');
  92. return false;
  93. }
  94. //追加权限
  95. $userpower = UserPower::getByUserId($user_id);
  96. if(!$userpower){
  97. $this->setError('Account not exist');
  98. return false;
  99. }
  100. $user->power = $userpower;
  101. $this->_user = $user;
  102. $this->_logined = true;
  103. $this->_token = $token;
  104. //初始化成功的事件
  105. Hook::listen("user_init_successed", $this->_user);
  106. return true;
  107. } else {
  108. $this->setError('You are not logged in');
  109. return false;
  110. }
  111. }
  112. /**
  113. * 注册用户
  114. *
  115. * @param string $username 用户名
  116. * @param string $password 密码
  117. * @param string $email 邮箱
  118. * @param string $mobile 手机号
  119. * @param array $extend 扩展参数
  120. * @return boolean
  121. */
  122. public function register($username, $password, $mobile = '', $extend = [])
  123. {
  124. // 检测用户名、昵称、手机号是否存在
  125. // if (User::getByUsername($username)) {
  126. // $this->setError('Username already exist');
  127. // return false;
  128. // }
  129. // if (User::getByNickname($username)) {
  130. // $this->setError('Nickname already exist');
  131. // return false;
  132. // }
  133. if ($mobile && User::getByMobile($mobile)) {
  134. $this->setError('Mobile already exist');
  135. return false;
  136. }
  137. $ids = User::column("u_id");
  138. $invite_no = User::column("invite_no");
  139. $uidsale = config("site.uidsale");
  140. $uidsale = explode(",", $uidsale);
  141. if (is_array($uidsale) && $uidsale && $ids) $ids = array_merge($ids, $uidsale);
  142. $ip = request()->ip();
  143. $time = time();
  144. $data = [
  145. 'u_id' => $this->getUinqueId(8, $ids),
  146. 'invite_no' => $this->getUinqueNo(8, $invite_no),
  147. 'username' => $username,
  148. // 'password' => $password,
  149. 'mobile' => $mobile,
  150. 'level' => 0,
  151. 'score' => 0,
  152. 'avatar' => isset($extend["avatar"]) ? $extend["avatar"] : '/assets/dc0f37f043e1e9f5240ed87e37f18740.png',
  153. 'image' => '/assets/9e41a766262bcbded449334a5cc0adfd.jpeg',
  154. ];
  155. //https://bansheng-1304213176.cos.ap-guangzhou.myqcloud.com/
  156. $params = array_merge($data, [
  157. 'nickname' => "gg_" . $data["u_id"],
  158. 'salt' => Random::alnum(),
  159. 'joinip' => $ip,
  160. 'logintime' => $time,
  161. 'loginip' => $ip,
  162. 'status' => 'normal'
  163. ]);
  164. // $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  165. $extend && $params = array_merge($params, $extend);
  166. //账号注册时需要开启事务,避免出现垃圾数据
  167. Db::startTrans();
  168. try {
  169. $user = User::create($params, true);
  170. $this->_user = User::get($user->id);
  171. //设置Token
  172. $this->_token = Random::uuid();
  173. Token::set($this->_token, $user->id, $this->keeptime);
  174. //设置登录状态
  175. $this->_logined = true;
  176. //初始化权限
  177. $userPowerWhere['user_id'] = $user->id;
  178. $userPowerData = Db::name('user_power')->where($userPowerWhere)->find();
  179. if (empty($userPowerData)) {
  180. $powerData = ['user_id' => $user->id];
  181. Db::name('user_power')->insertGetId($powerData);
  182. }
  183. //注册成功的事件
  184. Hook::listen("user_register_successed", $this->_user, $data);
  185. \app\common\model\NewBagHave::insert(["user_id" => $user->id, "createtime" => time()]);
  186. Db::commit();
  187. } catch (Exception $e) {
  188. $this->setError($e->getMessage());
  189. Db::rollback();
  190. return false;
  191. }
  192. return true;
  193. }
  194. /**
  195. * 生成不重复的随机数字
  196. */
  197. function getUinqueId($length = 8, $ids = [])
  198. {
  199. $newid = Random::build("nozero", $length);
  200. if (in_array($newid, $ids)) {
  201. $newid = $this->getUinqueId($length, $ids);
  202. }
  203. return $newid;
  204. }
  205. /**
  206. * 生成不重复的随机数字字母组合
  207. */
  208. function getUinqueNo($length = 8, $nos = [])
  209. {
  210. $newid = Random::build("alnum", $length);
  211. if (in_array($newid, $nos)) {
  212. $newid = $this->getUinqueNo($length, $nos);
  213. }
  214. return $newid;
  215. }
  216. /**
  217. * 用户登录
  218. *
  219. * @param string $account 账号,用户名、邮箱、手机号
  220. * @param string $password 密码
  221. * @return boolean
  222. */
  223. public function login($account, $password)
  224. {
  225. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  226. $user = User::get([$field => $account]);
  227. if (!$user) {
  228. $this->setError('Account is incorrect');
  229. return false;
  230. }
  231. if ($user->status != 'normal') {
  232. $this->setError('Account is locked');
  233. return false;
  234. }
  235. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  236. $this->setError('Password is incorrect');
  237. return false;
  238. }
  239. //直接登录会员
  240. $this->direct($user->id);
  241. return true;
  242. }
  243. /**
  244. * 退出
  245. *
  246. * @return boolean
  247. */
  248. public function logout()
  249. {
  250. if (!$this->_logined) {
  251. $this->setError('You are not logged in');
  252. return false;
  253. }
  254. //设置登录标识
  255. $this->_logined = false;
  256. //删除Token
  257. Token::delete($this->_token);
  258. //退出成功的事件
  259. Hook::listen("user_logout_successed", $this->_user);
  260. return true;
  261. }
  262. /**
  263. * 修改密码
  264. * @param string $newpassword 新密码
  265. * @param string $oldpassword 旧密码
  266. * @param bool $ignoreoldpassword 忽略旧密码
  267. * @return boolean
  268. */
  269. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  270. {
  271. if (!$this->_logined) {
  272. $this->setError('You are not logged in');
  273. return false;
  274. }
  275. //判断旧密码是否正确
  276. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  277. Db::startTrans();
  278. try {
  279. $salt = Random::alnum();
  280. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  281. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  282. // Token::delete($this->_token);
  283. // //修改密码成功的事件
  284. // Hook::listen("user_changepwd_successed", $this->_user);
  285. Db::commit();
  286. } catch (Exception $e) {
  287. Db::rollback();
  288. $this->setError($e->getMessage());
  289. return false;
  290. }
  291. return true;
  292. } else {
  293. $this->setError('Password is incorrect');
  294. return false;
  295. }
  296. }
  297. /**
  298. * 直接登录账号
  299. * @param int $user_id
  300. * @return boolean
  301. */
  302. public function direct($user_id)
  303. {
  304. $user = User::getById($user_id);
  305. if ($user) {
  306. $userpower = UserPower::getByUserId($user_id);
  307. if(!$userpower){
  308. return false;
  309. }
  310. Db::startTrans();
  311. try {
  312. // 微信内置浏览器时不请空用户的token,APP才清除所有token
  313. if (!strpos($_SERVER["HTTP_USER_AGENT"], "MicroMessenger")) {
  314. // 先清除所有token
  315. Token::clear($user->id);
  316. }
  317. $ip = request()->ip();
  318. $time = time();
  319. //记录本次登录的IP和时间
  320. $user->loginip = $ip;
  321. $user->logintime = $time;
  322. $user->save();
  323. $user->power = $userpower;// 追加权限
  324. $this->_user = $user;
  325. $this->_token = Random::uuid();
  326. Token::set($this->_token, $user->id, $this->keeptime);
  327. $this->_logined = true;
  328. //登录成功的事件
  329. Hook::listen("user_login_successed", $this->_user);
  330. Db::commit();
  331. } catch (Exception $e) {
  332. Db::rollback();
  333. $this->setError($e->getMessage());
  334. return false;
  335. }
  336. return true;
  337. } else {
  338. return false;
  339. }
  340. }
  341. /**
  342. * 检测是否是否有对应权限
  343. * @param string $path 控制器/方法
  344. * @param string $module 模块 默认为当前模块
  345. * @return boolean
  346. */
  347. public function check($path = null, $module = null)
  348. {
  349. if (!$this->_logined) {
  350. return false;
  351. }
  352. $ruleList = $this->getRuleList();
  353. $rules = [];
  354. foreach ($ruleList as $k => $v) {
  355. $rules[] = $v['name'];
  356. }
  357. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  358. $url = strtolower(str_replace('.', '/', $url));
  359. return in_array($url, $rules) ? true : false;
  360. }
  361. /**
  362. * 判断是否登录
  363. * @return boolean
  364. */
  365. public function isLogin()
  366. {
  367. if ($this->_logined) {
  368. return true;
  369. }
  370. return false;
  371. }
  372. /**
  373. * 获取当前Token
  374. * @return string
  375. */
  376. public function getToken()
  377. {
  378. return $this->_token;
  379. }
  380. /**
  381. * 获取会员基本信息
  382. */
  383. public function getUserinfo()
  384. {
  385. $data = $this->_user->toArray();
  386. // 获取粉丝数
  387. $fans = \app\common\model\ViewFans::where(["user_id" => $this->_user->id])->value("fans");
  388. $follows = \app\common\model\ViewFollows::where(["user_id" => $this->_user->id])->value("follows");
  389. $fansfollows["fans"] = $fans ? $fans : 0;
  390. $fansfollows["follows"] = $follows ? $follows : 0;
  391. $allowFields = $this->getAllowFields();
  392. $userinfo = array_intersect_key($data, array_flip($allowFields));
  393. $userinfo = array_merge($userinfo, Token::get($this->_token));
  394. $userinfo = array_merge($userinfo, $fansfollows);
  395. // 获取贵族信息
  396. $nobleInfo = $this->_user->getUserNobleInfo($this->_user->id);
  397. $userinfo = array_merge($userinfo, $nobleInfo);
  398. $usercar = "";
  399. $userheader = "";
  400. $userlight = "";
  401. $userpop = "";
  402. $userandroidpop = "";
  403. // 获取用户头像框和座驾信息
  404. $backResult = \app\common\model\AttireBack::field("file_image,gif_image,type,android_image")
  405. ->where(["user_id" => $this->_user->id, "is_using" => 1, "is_use" => 1, "duetime" => ["gt", time()]])->select();
  406. if ($backResult) {
  407. foreach ($backResult as $k => $v) {
  408. $v["type"] == 1 && $usercar = $v["gif_image"];
  409. $v["type"] == 2 && $userheader = $v["gif_image"];
  410. $v["type"] == 3 && $userlight = $v["file_image"];
  411. $v["type"] == 4 && $userpop = $v["file_image"];
  412. $v["type"] == 4 && $userandroidpop = $v["android_image"];
  413. }
  414. }
  415. // 获取我的推荐人的邀请码
  416. $preCode = \app\common\model\User::where(["id" => $this->_user->pre_userid])->value("invite_no");
  417. $userinfo["preCode"] = $preCode ? $preCode : "";
  418. $userinfo["usercar"] = $usercar;
  419. $userinfo["userheader"] = $userheader;
  420. $userinfo["userlight"] = $userlight;
  421. $userinfo["userpop"] = $userpop;
  422. $userinfo["userandroidpop"] = $userandroidpop;
  423. // 是否设置密码
  424. $userinfo['is_setpwd'] = $data['password'] ? 1 : 0;
  425. $field = 'id,age_id,constellation_id,province_id,city_id,desc';
  426. $fieldArr = explode(',',$field);
  427. $fieldTextArr = ['age_text','constellation_text','province_text','city_text','friends_num','look_num'];
  428. $fieldArr = array_merge($fieldArr,$fieldTextArr);
  429. $userData = model('User')->field($field)->where(['id'=>$this->_user->id])->find();
  430. foreach ($fieldArr as $key => $value) {
  431. $userinfo[$value] = isset($userData[$value]) ? $userData[$value] : '';
  432. }
  433. return $userinfo;
  434. }
  435. /**
  436. * 获取会员组别规则列表
  437. * @return array
  438. */
  439. public function getRuleList()
  440. {
  441. if ($this->rules) {
  442. return $this->rules;
  443. }
  444. $group = $this->_user->group;
  445. if (!$group) {
  446. return [];
  447. }
  448. $rules = explode(',', $group->rules);
  449. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  450. return $this->rules;
  451. }
  452. /**
  453. * 获取当前请求的URI
  454. * @return string
  455. */
  456. public function getRequestUri()
  457. {
  458. return $this->requestUri;
  459. }
  460. /**
  461. * 设置当前请求的URI
  462. * @param string $uri
  463. */
  464. public function setRequestUri($uri)
  465. {
  466. $this->requestUri = $uri;
  467. }
  468. /**
  469. * 获取允许输出的字段
  470. * @return array
  471. */
  472. public function getAllowFields()
  473. {
  474. return $this->allowFields;
  475. }
  476. /**
  477. * 设置允许输出的字段
  478. * @param array $fields
  479. */
  480. public function setAllowFields($fields)
  481. {
  482. $this->allowFields = $fields;
  483. }
  484. /**
  485. * 删除一个指定会员
  486. * @param int $user_id 会员ID
  487. * @return boolean
  488. */
  489. public function delete($user_id)
  490. {
  491. $user = User::get($user_id);
  492. if (!$user) {
  493. return false;
  494. }
  495. Db::startTrans();
  496. try {
  497. // 删除会员
  498. User::destroy($user_id);
  499. // 删除会员指定的所有Token
  500. Token::clear($user_id);
  501. Hook::listen("user_delete_successed", $user);
  502. Db::commit();
  503. } catch (Exception $e) {
  504. Db::rollback();
  505. $this->setError($e->getMessage());
  506. return false;
  507. }
  508. return true;
  509. }
  510. /**
  511. * 获取密码加密后的字符串
  512. * @param string $password 密码
  513. * @param string $salt 密码盐
  514. * @return string
  515. */
  516. public function getEncryptPassword($password, $salt = '')
  517. {
  518. return md5(md5($password) . $salt);
  519. }
  520. /**
  521. * 检测当前控制器和方法是否匹配传递的数组
  522. *
  523. * @param array $arr 需要验证权限的数组
  524. * @return boolean
  525. */
  526. public function match($arr = [])
  527. {
  528. $request = Request::instance();
  529. $arr = is_array($arr) ? $arr : explode(',', $arr);
  530. if (!$arr) {
  531. return false;
  532. }
  533. $arr = array_map('strtolower', $arr);
  534. // 是否存在
  535. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  536. return true;
  537. }
  538. // 没找到匹配
  539. return false;
  540. }
  541. /**
  542. * 设置会话有效时间
  543. * @param int $keeptime 默认为永久
  544. */
  545. public function keeptime($keeptime = 0)
  546. {
  547. $this->keeptime = $keeptime;
  548. }
  549. /**
  550. * 渲染用户数据
  551. * @param array $datalist 二维数组
  552. * @param mixed $fields 加载的字段列表
  553. * @param string $fieldkey 渲染的字段
  554. * @param string $renderkey 结果字段
  555. * @return array
  556. */
  557. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  558. {
  559. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  560. $ids = [];
  561. foreach ($datalist as $k => $v) {
  562. if (!isset($v[$fieldkey])) {
  563. continue;
  564. }
  565. $ids[] = $v[$fieldkey];
  566. }
  567. $list = [];
  568. if ($ids) {
  569. if (!in_array('id', $fields)) {
  570. $fields[] = 'id';
  571. }
  572. $ids = array_unique($ids);
  573. $selectlist = User::where('id', 'in', $ids)->column($fields);
  574. foreach ($selectlist as $k => $v) {
  575. $list[$v['id']] = $v;
  576. }
  577. }
  578. foreach ($datalist as $k => &$v) {
  579. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  580. }
  581. unset($v);
  582. return $datalist;
  583. }
  584. /**
  585. * 设置错误信息
  586. *
  587. * @param $error 错误信息
  588. * @return Auth
  589. */
  590. public function setError($error)
  591. {
  592. $this->_error = $error;
  593. return $this;
  594. }
  595. /**
  596. * 获取错误信息
  597. * @return string
  598. */
  599. public function getError()
  600. {
  601. return $this->_error ? __($this->_error) : '';
  602. }
  603. public function openid_register($wechat_openid = '', $extend = [])
  604. {
  605. /*if ($wechat_openid && User::getByOpenid($wechat_openid)) {
  606. $this->setError('openid已存在');
  607. return false;
  608. }
  609. $ip = request()->ip();
  610. $time = time();
  611. $introcode = User::column("introcode");
  612. $data = [
  613. 'wechat_openid' => $wechat_openid,
  614. //'avatar' => 'https://meet-1251365327.cos.ap-beijing.myqcloud.com/uploads/20220314/f57ebce8a72b823912904fe76eda0909.png',
  615. 'avatar' => $extend['gender'] == 1 ? config('avatar_boy') : config('avatar_girl'),//config('site.domain_cdnurl').'/avatar.png',
  616. 'introcode' => $this->getUinqueNo(6, $introcode),
  617. 'nickname' => get_rand_nick_name(),
  618. ];
  619. $params = array_merge($data, [
  620. 'salt' => Random::alnum(),
  621. 'jointime' => $time,
  622. 'joinip' => $ip,
  623. 'logintime' => $time,
  624. 'loginip' => $ip,
  625. 'prevtime' => $time,
  626. 'status' => 'normal'
  627. ]);
  628. $params = array_merge($params, $extend);
  629. //账号注册时需要开启事务,避免出现垃圾数据
  630. Db::startTrans();
  631. try {
  632. $user = User::create($params, true);
  633. $this->_user = User::get($user->id);
  634. $this->_user->u_id = $this->getUinqueId(8, $user->id);
  635. $this->_user->save();
  636. //设置Token
  637. $this->_token = Random::uuid();
  638. Token::set($this->_token, $user->id, $this->keeptime);
  639. //设置登录状态
  640. $this->_logined = true;
  641. //注册成功的事件
  642. Hook::listen("user_register_successed", $this->_user, $data);
  643. Db::commit();
  644. } catch (Exception $e) {
  645. $this->setError($e->getMessage());
  646. Db::rollback();
  647. return false;
  648. }*/
  649. return true;
  650. }
  651. }