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.
 
 
 
 
 
 

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