You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

565 lines
15 KiB

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