Auth.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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', 'nickname', 'mobile', 'avatar', 'gender','birthday','age',
  27. 'province','city','district','province_name','city_name','district_name','lng', 'lat',
  28. 'money','frozen','expect_ids','constellation','hobby_ids','profession','wechat','vip_duetime',
  29. 'wechat_auth','wechat_time','declaration','tag_ids','auth_time','is_auth','is_goddess',
  30. 'income','recharge_auth','view_count','invite_no','pre_user_id','invite_time','emcid', 'copy_mobile', 'is_auth_person', 'diamond'];
  31. public function __construct($options = [])
  32. {
  33. if ($config = Config::get('user')) {
  34. $this->config = array_merge($this->config, $config);
  35. }
  36. $this->options = array_merge($this->config, $options);
  37. }
  38. /**
  39. *
  40. * @param array $options 参数
  41. * @return Auth
  42. */
  43. public static function instance($options = [])
  44. {
  45. if (is_null(self::$instance)) {
  46. self::$instance = new static($options);
  47. }
  48. return self::$instance;
  49. }
  50. /**
  51. * 获取User模型
  52. * @return User
  53. */
  54. public function getUser()
  55. {
  56. return $this->_user;
  57. }
  58. /**
  59. * 兼容调用user模型的属性
  60. *
  61. * @param string $name
  62. * @return mixed
  63. */
  64. public function __get($name)
  65. {
  66. return $this->_user ? $this->_user->$name : null;
  67. }
  68. /**
  69. * 兼容调用user模型的属性
  70. */
  71. public function __isset($name)
  72. {
  73. return isset($this->_user) ? isset($this->_user->$name) : false;
  74. }
  75. /**
  76. * 根据Token初始化
  77. *
  78. * @param string $token Token
  79. * @return boolean
  80. */
  81. public function init($token)
  82. {
  83. if ($this->_logined) {
  84. return true;
  85. }
  86. if ($this->_error) {
  87. return false;
  88. }
  89. $data = Token::get($token);
  90. if (!$data) {
  91. return false;
  92. }
  93. $user_id = intval($data['user_id']);
  94. if ($user_id > 0) {
  95. $user = User::get($user_id);
  96. if (!$user) {
  97. $this->setError('Account not exist');
  98. return false;
  99. }
  100. if ($user['status'] == 'hidden') {
  101. $this->setError('Account is locked');
  102. return false;
  103. }
  104. if ($user['status'] == 'logout') {
  105. $this->setError('账户已注销');
  106. return false;
  107. }
  108. $this->_user = $user;
  109. $this->_logined = true;
  110. $this->_token = $token;
  111. //记录用户访问时间
  112. $info = Db::name('user_info')->where(['user_id' => $user_id])->find();
  113. if (!$info) {
  114. Db::name('user_info')->insertGetId(['user_id' => $user_id, 'asktime' => time()]);
  115. } else {
  116. $asktime_before = explode(',', $info['asktime']);
  117. if (count($asktime_before) < 20) {
  118. $asktime_now = $info['asktime'] . ',' . time();
  119. } else {
  120. unset($asktime_before[0]);
  121. $asktime_now = join(',', $asktime_before) . ',' . time();
  122. }
  123. Db::name('user_info')->where(['user_id' => $user_id])->setField('asktime', $asktime_now);
  124. }
  125. //初始化成功的事件
  126. Hook::listen("user_init_successed", $this->_user);
  127. return true;
  128. } else {
  129. $this->setError('You are not logged in');
  130. return false;
  131. }
  132. }
  133. /**
  134. * 注册用户
  135. *
  136. * @param string $username 用户名
  137. * @param string $password 密码
  138. * @param string $email 邮箱
  139. * @param string $mobile 手机号
  140. * @param array $extend 扩展参数
  141. * @return boolean
  142. */
  143. public function register($username, $password,$mobile = '', $extend = [])
  144. {
  145. // 检测用户名、昵称、邮箱、手机号是否存在
  146. if (User::getByUsername($username)) {
  147. $this->setError('Username already exist');
  148. return false;
  149. }
  150. if (User::getByNickname($username)) {
  151. $this->setError('Nickname already exist');
  152. return false;
  153. }
  154. if ($mobile && User::getByMobile($mobile)) {
  155. $this->setError('Mobile already exist');
  156. return false;
  157. }
  158. $invite_no = User::column("invite_no");
  159. $data = [
  160. 'invite_no' => $this->getUinqueNo(6,$invite_no),
  161. 'username' => $username,
  162. 'password' => $password,
  163. 'mobile' => $mobile,
  164. 'level' => 1,
  165. 'score' => 0,
  166. ];
  167. $params = array_merge($data, [
  168. 'salt' => Random::alnum(),
  169. 'logintime' => time(),
  170. 'status' => 'normal'
  171. ]);
  172. $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  173. // 获取默认头像和昵称和交友宣言
  174. $nickname_arr = array_column(\app\admin\model\website\Nickname::select(),'content');
  175. $avatar_arr = array_column(\app\admin\model\website\Avatar::select(),'content');
  176. $declaration_arr = array_column(\app\admin\model\website\Declaration::select(),'content');
  177. $params['nickname'] = $nickname_arr?$nickname_arr[array_rand($nickname_arr,1)]:'';
  178. $params['avatar'] = $avatar_arr?$avatar_arr[array_rand($avatar_arr,1)]:'';
  179. $params['declaration'] = $declaration_arr?$declaration_arr[array_rand($declaration_arr,1)]:'';
  180. $extend && $params = array_merge($params, $extend);
  181. //账号注册时需要开启事务,避免出现垃圾数据
  182. Db::startTrans();
  183. try {
  184. $user = User::create($params, true);
  185. $this->_user = User::get($user->id);
  186. //设置Token
  187. $this->_token = Random::uuid();
  188. Token::set($this->_token, $user->id, $this->keeptime);
  189. //设置登录状态
  190. $this->_logined = true;
  191. //注册成功的事件
  192. Hook::listen("user_register_successed", $this->_user, $data);
  193. Db::commit();
  194. //增加钻石
  195. //开启事务
  196. Db::startTrans();
  197. //修改用户钻石余额
  198. $res1 = Db::name('user')->where(['id' => $user->id])->setField('diamond', 100);
  199. // 添加钻石明细
  200. $_data['user_id'] = $user->id;
  201. $_data['diamond'] = 100;
  202. $_data['before'] = 0;
  203. $_data['after'] = 100;
  204. $_data['memo'] = '注册';
  205. $_data['createtime'] = time();
  206. $res2 = Db::name('user_diamond_log')->insertGetId($_data);
  207. if ($res1 && $res2) {
  208. Db::commit();
  209. } else {
  210. Db::rollback();
  211. }
  212. } catch (Exception $e) {
  213. $this->setError($e->getMessage());
  214. Db::rollback();
  215. return false;
  216. }
  217. return true;
  218. }
  219. /**
  220. * 生成不重复的随机数字字母组合
  221. */
  222. function getUinqueNo($length = 6,$nos = []) {
  223. $newid = Random::build("alnum",$length);
  224. if(in_array($newid,$nos)) {
  225. $this->getUinqueNo(6,$nos);
  226. }
  227. return $newid;
  228. }
  229. /**
  230. * 用户登录
  231. *
  232. * @param string $account 账号,用户名、邮箱、手机号
  233. * @param string $password 密码
  234. * @return boolean
  235. */
  236. public function login($account, $password)
  237. {
  238. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  239. $user = User::get([$field => $account]);
  240. if (!$user) {
  241. $this->setError('Account is incorrect');
  242. return false;
  243. }
  244. if ($user->status == 'hidden') {
  245. $this->setError('Account is locked');
  246. return false;
  247. }
  248. if ($user->status == 'logout') {
  249. $this->setError('账号已注销');
  250. return false;
  251. }
  252. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  253. $this->setError('Password is incorrect');
  254. return false;
  255. }
  256. //直接登录会员
  257. $this->direct($user->id);
  258. return true;
  259. }
  260. /**
  261. * 退出
  262. *
  263. * @return boolean
  264. */
  265. public function logout()
  266. {
  267. if (!$this->_logined) {
  268. $this->setError('You are not logged in');
  269. return false;
  270. }
  271. //设置登录标识
  272. $this->_logined = false;
  273. //删除Token
  274. Token::delete($this->_token);
  275. //退出成功的事件
  276. Hook::listen("user_logout_successed", $this->_user);
  277. return true;
  278. }
  279. /**
  280. * 修改密码
  281. * @param string $newpassword 新密码
  282. * @param string $oldpassword 旧密码
  283. * @param bool $ignoreoldpassword 忽略旧密码
  284. * @return boolean
  285. */
  286. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  287. {
  288. if (!$this->_logined) {
  289. $this->setError('You are not logged in');
  290. return false;
  291. }
  292. //判断旧密码是否正确
  293. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  294. Db::startTrans();
  295. try {
  296. $salt = Random::alnum();
  297. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  298. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  299. Token::delete($this->_token);
  300. //修改密码成功的事件
  301. Hook::listen("user_changepwd_successed", $this->_user);
  302. Db::commit();
  303. } catch (Exception $e) {
  304. Db::rollback();
  305. $this->setError($e->getMessage());
  306. return false;
  307. }
  308. return true;
  309. } else {
  310. $this->setError('Password is incorrect');
  311. return false;
  312. }
  313. }
  314. /**
  315. * 直接登录账号
  316. * @param int $user_id
  317. * @return boolean
  318. */
  319. public function direct($user_id)
  320. {
  321. $user = User::get($user_id);
  322. if ($user) {
  323. Db::startTrans();
  324. try {
  325. // 先清除所有token
  326. Token::clear($user->id);
  327. $ip = request()->ip();
  328. $time = time();
  329. $user->logintime = $time;
  330. $user->save();
  331. $this->_user = $user;
  332. $this->_token = Random::uuid();
  333. Token::set($this->_token, $user->id, $this->keeptime);
  334. $this->_logined = true;
  335. //登录成功的事件
  336. Hook::listen("user_login_successed", $this->_user);
  337. Db::commit();
  338. } catch (Exception $e) {
  339. Db::rollback();
  340. $this->setError($e->getMessage());
  341. return false;
  342. }
  343. return true;
  344. } else {
  345. return false;
  346. }
  347. }
  348. /**
  349. * 检测是否是否有对应权限
  350. * @param string $path 控制器/方法
  351. * @param string $module 模块 默认为当前模块
  352. * @return boolean
  353. */
  354. public function check($path = null, $module = null)
  355. {
  356. if (!$this->_logined) {
  357. return false;
  358. }
  359. $ruleList = $this->getRuleList();
  360. $rules = [];
  361. foreach ($ruleList as $k => $v) {
  362. $rules[] = $v['name'];
  363. }
  364. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  365. $url = strtolower(str_replace('.', '/', $url));
  366. return in_array($url, $rules) ? true : false;
  367. }
  368. /**
  369. * 判断是否登录
  370. * @return boolean
  371. */
  372. public function isLogin()
  373. {
  374. if ($this->_logined) {
  375. return true;
  376. }
  377. return false;
  378. }
  379. /**
  380. * 获取当前Token
  381. * @return string
  382. */
  383. public function getToken()
  384. {
  385. return $this->_token;
  386. }
  387. /**
  388. * 获取会员基本信息
  389. */
  390. public function getUserinfo()
  391. {
  392. $data = $this->_user->toArray();
  393. $allowFields = $this->getAllowFields();
  394. $userinfo = array_intersect_key($data, array_flip($allowFields));
  395. $userinfo = array_merge($userinfo, Token::get($this->_token));
  396. if($userinfo['vip_duetime'] > time()) $userinfo['is_vip'] = 1;
  397. elseif($userinfo['vip_duetime'] > 0) $userinfo['is_vip'] = -1;
  398. else $userinfo['is_vip'] = 0;
  399. $userinfo['vip_duetime'] = date('Y-m-d H:i:s',$userinfo['vip_duetime']);
  400. $userinfo['hobby_ids'] = \app\common\model\Hobby::getHobbyNames($userinfo['hobby_ids']);
  401. $userinfo['expect_ids'] = \app\common\model\Expect::getExpectNames($userinfo['expect_ids']);
  402. $userinfo['nickname_auth_stauts'] = \app\common\model\NicknameAuth::getAuthStatus($userinfo['id'],$userinfo['nickname']);
  403. $userinfo['avatar_auth_stauts'] = \app\common\model\AvatarAuth::getAuthStatus($userinfo['id'],$userinfo['avatar']);
  404. $userinfo['wechat_auth_stauts'] = \app\common\model\WechatAuth::getAuthStatus($userinfo['id'],$userinfo['wechat']);
  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. }