Auth.php 16 KB

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