Auth.php 14 KB

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