Auth.php 16 KB

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