Auth.php 15 KB

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