Auth.php 16 KB

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