Auth.php 15 KB

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