Auth.php 16 KB

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