Auth.php 16 KB

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