Auth.php 17 KB

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