Auth.php 15 KB

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