Auth.php 15 KB

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