Auth.php 16 KB

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