Auth.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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'] != 'normal') {
  101. $this->setError('Account is locked');
  102. return false;
  103. }
  104. $this->_user = $user;
  105. $this->_logined = true;
  106. $this->_token = $token;
  107. //记录用户访问时间
  108. $info = Db::name('user_info')->where(['user_id' => $user_id])->find();
  109. if (!$info) {
  110. Db::name('user_info')->insertGetId(['user_id' => $user_id, 'asktime' => time()]);
  111. } else {
  112. $asktime_before = explode(',', $info['asktime']);
  113. if (count($asktime_before) < 20) {
  114. $asktime_now = $info['asktime'] . ',' . time();
  115. } else {
  116. unset($asktime_before[0]);
  117. $asktime_now = join(',', $asktime_before) . ',' . time();
  118. }
  119. Db::name('user_info')->where(['user_id' => $user_id])->setField('asktime', $asktime_now);
  120. }
  121. //初始化成功的事件
  122. Hook::listen("user_init_successed", $this->_user);
  123. return true;
  124. } else {
  125. $this->setError('You are not logged in');
  126. return false;
  127. }
  128. }
  129. /**
  130. * 注册用户
  131. *
  132. * @param string $username 用户名
  133. * @param string $password 密码
  134. * @param string $email 邮箱
  135. * @param string $mobile 手机号
  136. * @param array $extend 扩展参数
  137. * @return boolean
  138. */
  139. public function register($username, $password,$mobile = '', $extend = [])
  140. {
  141. // 检测用户名、昵称、邮箱、手机号是否存在
  142. if (User::getByUsername($username)) {
  143. $this->setError('Username already exist');
  144. return false;
  145. }
  146. if (User::getByNickname($username)) {
  147. $this->setError('Nickname already exist');
  148. return false;
  149. }
  150. if ($mobile && User::getByMobile($mobile)) {
  151. $this->setError('Mobile already exist');
  152. return false;
  153. }
  154. $invite_no = User::column("invite_no");
  155. $data = [
  156. 'invite_no' => $this->getUinqueNo(6,$invite_no),
  157. 'username' => $username,
  158. 'password' => $password,
  159. 'mobile' => $mobile,
  160. 'level' => 1,
  161. 'score' => 0,
  162. ];
  163. $params = array_merge($data, [
  164. 'salt' => Random::alnum(),
  165. 'logintime' => time(),
  166. 'status' => 'normal'
  167. ]);
  168. $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  169. // 获取默认头像和昵称和交友宣言
  170. $nickname_arr = array_column(\app\admin\model\website\Nickname::select(),'content');
  171. $avatar_arr = array_column(\app\admin\model\website\Avatar::select(),'content');
  172. $declaration_arr = array_column(\app\admin\model\website\Declaration::select(),'content');
  173. $params['nickname'] = $nickname_arr?$nickname_arr[array_rand($nickname_arr,1)]:'';
  174. $params['avatar'] = $avatar_arr?$avatar_arr[array_rand($avatar_arr,1)]:'';
  175. $params['declaration'] = $declaration_arr?$declaration_arr[array_rand($declaration_arr,1)]:'';
  176. $extend && $params = array_merge($params, $extend);
  177. //账号注册时需要开启事务,避免出现垃圾数据
  178. Db::startTrans();
  179. try {
  180. $user = User::create($params, true);
  181. $this->_user = User::get($user->id);
  182. //设置Token
  183. $this->_token = Random::uuid();
  184. Token::set($this->_token, $user->id, $this->keeptime);
  185. //设置登录状态
  186. $this->_logined = true;
  187. //注册成功的事件
  188. Hook::listen("user_register_successed", $this->_user, $data);
  189. Db::commit();
  190. } catch (Exception $e) {
  191. $this->setError($e->getMessage());
  192. Db::rollback();
  193. return false;
  194. }
  195. return true;
  196. }
  197. /**
  198. * 生成不重复的随机数字字母组合
  199. */
  200. function getUinqueNo($length = 6,$nos = []) {
  201. $newid = Random::build("alnum",$length);
  202. if(in_array($newid,$nos)) {
  203. $this->getUinqueNo(6,$nos);
  204. }
  205. return $newid;
  206. }
  207. /**
  208. * 用户登录
  209. *
  210. * @param string $account 账号,用户名、邮箱、手机号
  211. * @param string $password 密码
  212. * @return boolean
  213. */
  214. public function login($account, $password)
  215. {
  216. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  217. $user = User::get([$field => $account]);
  218. if (!$user) {
  219. $this->setError('Account is incorrect');
  220. return false;
  221. }
  222. if ($user->status != 'normal') {
  223. $this->setError('Account is locked');
  224. return false;
  225. }
  226. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  227. $this->setError('Password is incorrect');
  228. return false;
  229. }
  230. //直接登录会员
  231. $this->direct($user->id);
  232. return true;
  233. }
  234. /**
  235. * 退出
  236. *
  237. * @return boolean
  238. */
  239. public function logout()
  240. {
  241. if (!$this->_logined) {
  242. $this->setError('You are not logged in');
  243. return false;
  244. }
  245. //设置登录标识
  246. $this->_logined = false;
  247. //删除Token
  248. Token::delete($this->_token);
  249. //退出成功的事件
  250. Hook::listen("user_logout_successed", $this->_user);
  251. return true;
  252. }
  253. /**
  254. * 修改密码
  255. * @param string $newpassword 新密码
  256. * @param string $oldpassword 旧密码
  257. * @param bool $ignoreoldpassword 忽略旧密码
  258. * @return boolean
  259. */
  260. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  261. {
  262. if (!$this->_logined) {
  263. $this->setError('You are not logged in');
  264. return false;
  265. }
  266. //判断旧密码是否正确
  267. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  268. Db::startTrans();
  269. try {
  270. $salt = Random::alnum();
  271. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  272. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  273. Token::delete($this->_token);
  274. //修改密码成功的事件
  275. Hook::listen("user_changepwd_successed", $this->_user);
  276. Db::commit();
  277. } catch (Exception $e) {
  278. Db::rollback();
  279. $this->setError($e->getMessage());
  280. return false;
  281. }
  282. return true;
  283. } else {
  284. $this->setError('Password is incorrect');
  285. return false;
  286. }
  287. }
  288. /**
  289. * 直接登录账号
  290. * @param int $user_id
  291. * @return boolean
  292. */
  293. public function direct($user_id)
  294. {
  295. $user = User::get($user_id);
  296. if ($user) {
  297. Db::startTrans();
  298. try {
  299. // 先清除所有token
  300. Token::clear($user->id);
  301. $ip = request()->ip();
  302. $time = time();
  303. $user->logintime = $time;
  304. $user->save();
  305. $this->_user = $user;
  306. $this->_token = Random::uuid();
  307. Token::set($this->_token, $user->id, $this->keeptime);
  308. $this->_logined = true;
  309. //登录成功的事件
  310. Hook::listen("user_login_successed", $this->_user);
  311. Db::commit();
  312. } catch (Exception $e) {
  313. Db::rollback();
  314. $this->setError($e->getMessage());
  315. return false;
  316. }
  317. return true;
  318. } else {
  319. return false;
  320. }
  321. }
  322. /**
  323. * 检测是否是否有对应权限
  324. * @param string $path 控制器/方法
  325. * @param string $module 模块 默认为当前模块
  326. * @return boolean
  327. */
  328. public function check($path = null, $module = null)
  329. {
  330. if (!$this->_logined) {
  331. return false;
  332. }
  333. $ruleList = $this->getRuleList();
  334. $rules = [];
  335. foreach ($ruleList as $k => $v) {
  336. $rules[] = $v['name'];
  337. }
  338. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  339. $url = strtolower(str_replace('.', '/', $url));
  340. return in_array($url, $rules) ? true : false;
  341. }
  342. /**
  343. * 判断是否登录
  344. * @return boolean
  345. */
  346. public function isLogin()
  347. {
  348. if ($this->_logined) {
  349. return true;
  350. }
  351. return false;
  352. }
  353. /**
  354. * 获取当前Token
  355. * @return string
  356. */
  357. public function getToken()
  358. {
  359. return $this->_token;
  360. }
  361. /**
  362. * 获取会员基本信息
  363. */
  364. public function getUserinfo()
  365. {
  366. $data = $this->_user->toArray();
  367. $allowFields = $this->getAllowFields();
  368. $userinfo = array_intersect_key($data, array_flip($allowFields));
  369. $userinfo = array_merge($userinfo, Token::get($this->_token));
  370. if($userinfo['vip_duetime'] > time()) $userinfo['is_vip'] = 1;
  371. elseif($userinfo['vip_duetime'] > 0) $userinfo['is_vip'] = -1;
  372. else $userinfo['is_vip'] = 0;
  373. $userinfo['vip_duetime'] = date('Y-m-d H:i:s',$userinfo['vip_duetime']);
  374. $userinfo['hobby_ids'] = \app\common\model\Hobby::getHobbyNames($userinfo['hobby_ids']);
  375. $userinfo['expect_ids'] = \app\common\model\Expect::getExpectNames($userinfo['expect_ids']);
  376. $userinfo['nickname_auth_stauts'] = \app\common\model\NicknameAuth::getAuthStatus($userinfo['id'],$userinfo['nickname']);
  377. $userinfo['avatar_auth_stauts'] = \app\common\model\AvatarAuth::getAuthStatus($userinfo['id'],$userinfo['avatar']);
  378. $userinfo['wechat_auth_stauts'] = \app\common\model\WechatAuth::getAuthStatus($userinfo['id'],$userinfo['wechat']);
  379. return $userinfo;
  380. }
  381. /**
  382. * 获取会员组别规则列表
  383. * @return array
  384. */
  385. public function getRuleList()
  386. {
  387. if ($this->rules) {
  388. return $this->rules;
  389. }
  390. $group = $this->_user->group;
  391. if (!$group) {
  392. return [];
  393. }
  394. $rules = explode(',', $group->rules);
  395. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  396. return $this->rules;
  397. }
  398. /**
  399. * 获取当前请求的URI
  400. * @return string
  401. */
  402. public function getRequestUri()
  403. {
  404. return $this->requestUri;
  405. }
  406. /**
  407. * 设置当前请求的URI
  408. * @param string $uri
  409. */
  410. public function setRequestUri($uri)
  411. {
  412. $this->requestUri = $uri;
  413. }
  414. /**
  415. * 获取允许输出的字段
  416. * @return array
  417. */
  418. public function getAllowFields()
  419. {
  420. return $this->allowFields;
  421. }
  422. /**
  423. * 设置允许输出的字段
  424. * @param array $fields
  425. */
  426. public function setAllowFields($fields)
  427. {
  428. $this->allowFields = $fields;
  429. }
  430. /**
  431. * 删除一个指定会员
  432. * @param int $user_id 会员ID
  433. * @return boolean
  434. */
  435. public function delete($user_id)
  436. {
  437. $user = User::get($user_id);
  438. if (!$user) {
  439. return false;
  440. }
  441. Db::startTrans();
  442. try {
  443. // 删除会员
  444. User::destroy($user_id);
  445. // 删除会员指定的所有Token
  446. Token::clear($user_id);
  447. Hook::listen("user_delete_successed", $user);
  448. Db::commit();
  449. } catch (Exception $e) {
  450. Db::rollback();
  451. $this->setError($e->getMessage());
  452. return false;
  453. }
  454. return true;
  455. }
  456. /**
  457. * 获取密码加密后的字符串
  458. * @param string $password 密码
  459. * @param string $salt 密码盐
  460. * @return string
  461. */
  462. public function getEncryptPassword($password, $salt = '')
  463. {
  464. return md5(md5($password) . $salt);
  465. }
  466. /**
  467. * 检测当前控制器和方法是否匹配传递的数组
  468. *
  469. * @param array $arr 需要验证权限的数组
  470. * @return boolean
  471. */
  472. public function match($arr = [])
  473. {
  474. $request = Request::instance();
  475. $arr = is_array($arr) ? $arr : explode(',', $arr);
  476. if (!$arr) {
  477. return false;
  478. }
  479. $arr = array_map('strtolower', $arr);
  480. // 是否存在
  481. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  482. return true;
  483. }
  484. // 没找到匹配
  485. return false;
  486. }
  487. /**
  488. * 设置会话有效时间
  489. * @param int $keeptime 默认为永久
  490. */
  491. public function keeptime($keeptime = 0)
  492. {
  493. $this->keeptime = $keeptime;
  494. }
  495. /**
  496. * 渲染用户数据
  497. * @param array $datalist 二维数组
  498. * @param mixed $fields 加载的字段列表
  499. * @param string $fieldkey 渲染的字段
  500. * @param string $renderkey 结果字段
  501. * @return array
  502. */
  503. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  504. {
  505. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  506. $ids = [];
  507. foreach ($datalist as $k => $v) {
  508. if (!isset($v[$fieldkey])) {
  509. continue;
  510. }
  511. $ids[] = $v[$fieldkey];
  512. }
  513. $list = [];
  514. if ($ids) {
  515. if (!in_array('id', $fields)) {
  516. $fields[] = 'id';
  517. }
  518. $ids = array_unique($ids);
  519. $selectlist = User::where('id', 'in', $ids)->column($fields);
  520. foreach ($selectlist as $k => $v) {
  521. $list[$v['id']] = $v;
  522. }
  523. }
  524. foreach ($datalist as $k => &$v) {
  525. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  526. }
  527. unset($v);
  528. return $datalist;
  529. }
  530. /**
  531. * 设置错误信息
  532. *
  533. * @param $error 错误信息
  534. * @return Auth
  535. */
  536. public function setError($error)
  537. {
  538. $this->_error = $error;
  539. return $this;
  540. }
  541. /**
  542. * 获取错误信息
  543. * @return string
  544. */
  545. public function getError()
  546. {
  547. return $this->_error ? __($this->_error) : '';
  548. }
  549. }