Auth.php 16 KB

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