Auth.php 18 KB

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