Auth.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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' => "bans_" . $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. Hook::listen("user_register_successed", $this->_user, $data);
  178. \app\common\model\NewBagHave::insert(["user_id" => $user->id, "createtime" => time()]);
  179. Db::commit();
  180. } catch (Exception $e) {
  181. $this->setError($e->getMessage());
  182. Db::rollback();
  183. return false;
  184. }
  185. return true;
  186. }
  187. /**
  188. * 生成不重复的随机数字
  189. */
  190. function getUinqueId($length = 8, $ids = [])
  191. {
  192. $newid = Random::build("nozero", $length);
  193. if (in_array($newid, $ids)) {
  194. $newid = $this->getUinqueId($length, $ids);
  195. }
  196. return $newid;
  197. }
  198. /**
  199. * 生成不重复的随机数字字母组合
  200. */
  201. function getUinqueNo($length = 8, $nos = [])
  202. {
  203. $newid = Random::build("alnum", $length);
  204. if (in_array($newid, $nos)) {
  205. $newid = $this->getUinqueNo($length, $nos);
  206. }
  207. return $newid;
  208. }
  209. /**
  210. * 用户登录
  211. *
  212. * @param string $account 账号,用户名、邮箱、手机号
  213. * @param string $password 密码
  214. * @return boolean
  215. */
  216. public function login($account, $password)
  217. {
  218. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  219. $user = User::get([$field => $account]);
  220. if (!$user) {
  221. $this->setError('Account is incorrect');
  222. return false;
  223. }
  224. if ($user->status != 'normal') {
  225. $this->setError('Account is locked');
  226. return false;
  227. }
  228. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  229. $this->setError('Password is incorrect');
  230. return false;
  231. }
  232. //直接登录会员
  233. $this->direct($user->id);
  234. return true;
  235. }
  236. /**
  237. * 退出
  238. *
  239. * @return boolean
  240. */
  241. public function logout()
  242. {
  243. if (!$this->_logined) {
  244. $this->setError('You are not logged in');
  245. return false;
  246. }
  247. //设置登录标识
  248. $this->_logined = false;
  249. //删除Token
  250. Token::delete($this->_token);
  251. //退出成功的事件
  252. Hook::listen("user_logout_successed", $this->_user);
  253. return true;
  254. }
  255. /**
  256. * 修改密码
  257. * @param string $newpassword 新密码
  258. * @param string $oldpassword 旧密码
  259. * @param bool $ignoreoldpassword 忽略旧密码
  260. * @return boolean
  261. */
  262. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  263. {
  264. if (!$this->_logined) {
  265. $this->setError('You are not logged in');
  266. return false;
  267. }
  268. //判断旧密码是否正确
  269. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  270. Db::startTrans();
  271. try {
  272. $salt = Random::alnum();
  273. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  274. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  275. // Token::delete($this->_token);
  276. // //修改密码成功的事件
  277. // Hook::listen("user_changepwd_successed", $this->_user);
  278. Db::commit();
  279. } catch (Exception $e) {
  280. Db::rollback();
  281. $this->setError($e->getMessage());
  282. return false;
  283. }
  284. return true;
  285. } else {
  286. $this->setError('Password is incorrect');
  287. return false;
  288. }
  289. }
  290. /**
  291. * 直接登录账号
  292. * @param int $user_id
  293. * @return boolean
  294. */
  295. public function direct($user_id)
  296. {
  297. $user = User::getById($user_id);
  298. if ($user) {
  299. $userpower = UserPower::getByUserId($user_id);
  300. if(!$userpower){
  301. return false;
  302. }
  303. Db::startTrans();
  304. try {
  305. // 微信内置浏览器时不请空用户的token,APP才清除所有token
  306. if (!strpos($_SERVER["HTTP_USER_AGENT"], "MicroMessenger")) {
  307. // 先清除所有token
  308. Token::clear($user->id);
  309. }
  310. $ip = request()->ip();
  311. $time = time();
  312. //记录本次登录的IP和时间
  313. $user->loginip = $ip;
  314. $user->logintime = $time;
  315. $user->save();
  316. $user->power = $userpower;// 追加权限
  317. $this->_user = $user;
  318. $this->_token = Random::uuid();
  319. Token::set($this->_token, $user->id, $this->keeptime);
  320. $this->_logined = true;
  321. //登录成功的事件
  322. Hook::listen("user_login_successed", $this->_user);
  323. Db::commit();
  324. } catch (Exception $e) {
  325. Db::rollback();
  326. $this->setError($e->getMessage());
  327. return false;
  328. }
  329. return true;
  330. } else {
  331. return false;
  332. }
  333. }
  334. /**
  335. * 检测是否是否有对应权限
  336. * @param string $path 控制器/方法
  337. * @param string $module 模块 默认为当前模块
  338. * @return boolean
  339. */
  340. public function check($path = null, $module = null)
  341. {
  342. if (!$this->_logined) {
  343. return false;
  344. }
  345. $ruleList = $this->getRuleList();
  346. $rules = [];
  347. foreach ($ruleList as $k => $v) {
  348. $rules[] = $v['name'];
  349. }
  350. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  351. $url = strtolower(str_replace('.', '/', $url));
  352. return in_array($url, $rules) ? true : false;
  353. }
  354. /**
  355. * 判断是否登录
  356. * @return boolean
  357. */
  358. public function isLogin()
  359. {
  360. if ($this->_logined) {
  361. return true;
  362. }
  363. return false;
  364. }
  365. /**
  366. * 获取当前Token
  367. * @return string
  368. */
  369. public function getToken()
  370. {
  371. return $this->_token;
  372. }
  373. /**
  374. * 获取会员基本信息
  375. */
  376. public function getUserinfo()
  377. {
  378. $data = $this->_user->toArray();
  379. // 获取粉丝数
  380. $fans = \app\common\model\ViewFans::where(["user_id" => $this->_user->id])->value("fans");
  381. $follows = \app\common\model\ViewFollows::where(["user_id" => $this->_user->id])->value("follows");
  382. $fansfollows["fans"] = $fans ? $fans : 0;
  383. $fansfollows["follows"] = $follows ? $follows : 0;
  384. $allowFields = $this->getAllowFields();
  385. $userinfo = array_intersect_key($data, array_flip($allowFields));
  386. $userinfo = array_merge($userinfo, Token::get($this->_token));
  387. $userinfo = array_merge($userinfo, $fansfollows);
  388. // 获取贵族信息
  389. $nobleInfo = $this->_user->getUserNobleInfo($this->_user->id);
  390. $userinfo = array_merge($userinfo, $nobleInfo);
  391. $usercar = "";
  392. $userheader = "";
  393. $userlight = "";
  394. $userpop = "";
  395. $userandroidpop = "";
  396. // 获取用户头像框和座驾信息
  397. $backResult = \app\common\model\AttireBack::field("file_image,gif_image,type,android_image")
  398. ->where(["user_id" => $this->_user->id, "is_using" => 1, "is_use" => 1, "duetime" => ["gt", time()]])->select();
  399. if ($backResult) {
  400. foreach ($backResult as $k => $v) {
  401. $v["type"] == 1 && $usercar = $v["gif_image"];
  402. $v["type"] == 2 && $userheader = $v["gif_image"];
  403. $v["type"] == 3 && $userlight = $v["file_image"];
  404. $v["type"] == 4 && $userpop = $v["file_image"];
  405. $v["type"] == 4 && $userandroidpop = $v["android_image"];
  406. }
  407. }
  408. // 获取我的推荐人的邀请码
  409. $preCode = \app\common\model\User::where(["id" => $this->_user->pre_userid])->value("invite_no");
  410. $userinfo["preCode"] = $preCode ? $preCode : "";
  411. $userinfo["usercar"] = $usercar;
  412. $userinfo["userheader"] = $userheader;
  413. $userinfo["userlight"] = $userlight;
  414. $userinfo["userpop"] = $userpop;
  415. $userinfo["userandroidpop"] = $userandroidpop;
  416. // 是否设置密码
  417. $userinfo['is_setpwd'] = $data['password'] ? 1 : 0;
  418. return $userinfo;
  419. }
  420. /**
  421. * 获取会员组别规则列表
  422. * @return array
  423. */
  424. public function getRuleList()
  425. {
  426. if ($this->rules) {
  427. return $this->rules;
  428. }
  429. $group = $this->_user->group;
  430. if (!$group) {
  431. return [];
  432. }
  433. $rules = explode(',', $group->rules);
  434. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  435. return $this->rules;
  436. }
  437. /**
  438. * 获取当前请求的URI
  439. * @return string
  440. */
  441. public function getRequestUri()
  442. {
  443. return $this->requestUri;
  444. }
  445. /**
  446. * 设置当前请求的URI
  447. * @param string $uri
  448. */
  449. public function setRequestUri($uri)
  450. {
  451. $this->requestUri = $uri;
  452. }
  453. /**
  454. * 获取允许输出的字段
  455. * @return array
  456. */
  457. public function getAllowFields()
  458. {
  459. return $this->allowFields;
  460. }
  461. /**
  462. * 设置允许输出的字段
  463. * @param array $fields
  464. */
  465. public function setAllowFields($fields)
  466. {
  467. $this->allowFields = $fields;
  468. }
  469. /**
  470. * 删除一个指定会员
  471. * @param int $user_id 会员ID
  472. * @return boolean
  473. */
  474. public function delete($user_id)
  475. {
  476. $user = User::get($user_id);
  477. if (!$user) {
  478. return false;
  479. }
  480. Db::startTrans();
  481. try {
  482. // 删除会员
  483. User::destroy($user_id);
  484. // 删除会员指定的所有Token
  485. Token::clear($user_id);
  486. Hook::listen("user_delete_successed", $user);
  487. Db::commit();
  488. } catch (Exception $e) {
  489. Db::rollback();
  490. $this->setError($e->getMessage());
  491. return false;
  492. }
  493. return true;
  494. }
  495. /**
  496. * 获取密码加密后的字符串
  497. * @param string $password 密码
  498. * @param string $salt 密码盐
  499. * @return string
  500. */
  501. public function getEncryptPassword($password, $salt = '')
  502. {
  503. return md5(md5($password) . $salt);
  504. }
  505. /**
  506. * 检测当前控制器和方法是否匹配传递的数组
  507. *
  508. * @param array $arr 需要验证权限的数组
  509. * @return boolean
  510. */
  511. public function match($arr = [])
  512. {
  513. $request = Request::instance();
  514. $arr = is_array($arr) ? $arr : explode(',', $arr);
  515. if (!$arr) {
  516. return false;
  517. }
  518. $arr = array_map('strtolower', $arr);
  519. // 是否存在
  520. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  521. return true;
  522. }
  523. // 没找到匹配
  524. return false;
  525. }
  526. /**
  527. * 设置会话有效时间
  528. * @param int $keeptime 默认为永久
  529. */
  530. public function keeptime($keeptime = 0)
  531. {
  532. $this->keeptime = $keeptime;
  533. }
  534. /**
  535. * 渲染用户数据
  536. * @param array $datalist 二维数组
  537. * @param mixed $fields 加载的字段列表
  538. * @param string $fieldkey 渲染的字段
  539. * @param string $renderkey 结果字段
  540. * @return array
  541. */
  542. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  543. {
  544. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  545. $ids = [];
  546. foreach ($datalist as $k => $v) {
  547. if (!isset($v[$fieldkey])) {
  548. continue;
  549. }
  550. $ids[] = $v[$fieldkey];
  551. }
  552. $list = [];
  553. if ($ids) {
  554. if (!in_array('id', $fields)) {
  555. $fields[] = 'id';
  556. }
  557. $ids = array_unique($ids);
  558. $selectlist = User::where('id', 'in', $ids)->column($fields);
  559. foreach ($selectlist as $k => $v) {
  560. $list[$v['id']] = $v;
  561. }
  562. }
  563. foreach ($datalist as $k => &$v) {
  564. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  565. }
  566. unset($v);
  567. return $datalist;
  568. }
  569. /**
  570. * 设置错误信息
  571. *
  572. * @param $error 错误信息
  573. * @return Auth
  574. */
  575. public function setError($error)
  576. {
  577. $this->_error = $error;
  578. return $this;
  579. }
  580. /**
  581. * 获取错误信息
  582. * @return string
  583. */
  584. public function getError()
  585. {
  586. return $this->_error ? __($this->_error) : '';
  587. }
  588. }