Auth.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. <?php
  2. namespace app\common\library;
  3. use app\common\model\User;
  4. use app\common\model\UserPower;
  5. use app\common\model\UserRule;
  6. use fast\Random;
  7. use think\Config;
  8. use think\Db;
  9. use think\Exception;
  10. use think\Hook;
  11. use think\Request;
  12. use think\Validate;
  13. class Auth
  14. {
  15. protected static $instance = null;
  16. protected $_error = '';
  17. protected $_logined = false;
  18. protected $_user = null;
  19. protected $_token = '';
  20. //Token默认有效时长
  21. protected $keeptime = 2592000;
  22. protected $requestUri = '';
  23. protected $rules = [];
  24. //默认配置
  25. protected $config = [];
  26. protected $options = [];
  27. protected $allowFields = ['id', 'u_id', 'username', 'nickname', 'mobile', 'pre_userid', 'has_info', 'is_auth',
  28. 'is_guild', 'guild_id', 'avatar', 'image', 'gender', 'age_id',
  29. 'wealth_level','charm_level',
  30. 'job_id', 'longitude', 'latitude','province_id','city_id','desc','is_cool','openid'
  31. ];
  32. public function __construct($options = [])
  33. {
  34. if ($config = Config::get('user')) {
  35. $this->config = array_merge($this->config, $config);
  36. }
  37. $this->options = array_merge($this->config, $options);
  38. }
  39. /**
  40. *
  41. * @param array $options 参数
  42. * @return Auth
  43. */
  44. public static function instance($options = [])
  45. {
  46. if (is_null(self::$instance)) {
  47. self::$instance = new static($options);
  48. }
  49. return self::$instance;
  50. }
  51. /**
  52. * 获取User模型
  53. * @return User
  54. */
  55. public function getUser()
  56. {
  57. return $this->_user;
  58. }
  59. /**
  60. * 兼容调用user模型的属性
  61. *
  62. * @param string $name
  63. * @return mixed
  64. */
  65. public function __get($name)
  66. {
  67. return $this->_user ? $this->_user->$name : null;
  68. }
  69. /**
  70. * 根据Token初始化
  71. *
  72. * @param string $token Token
  73. * @return boolean
  74. */
  75. public function init($token)
  76. {
  77. if ($this->_logined) {
  78. return true;
  79. }
  80. if ($this->_error) {
  81. return false;
  82. }
  83. $data = Token::get($token);
  84. if (!$data) {
  85. return false;
  86. }
  87. $user_id = intval($data['user_id']);
  88. if ($user_id > 0) {
  89. $user = User::get($user_id);
  90. if (!$user) {
  91. $this->setError('Account not exist');
  92. return false;
  93. }
  94. if ($user['status'] == -1) {
  95. $this->setError('账号已注销');
  96. return false;
  97. }
  98. if ($user['status'] != 1) {
  99. $this->setError('Account is locked');
  100. return false;
  101. }
  102. //追加权限
  103. $userpower = UserPower::getByUserId($user_id);
  104. if(!$userpower){
  105. $this->setError('Account not exist');
  106. return false;
  107. }
  108. $user->power = $userpower;
  109. //这个项目没用到user_power的禁言
  110. /*if ($userpower['private_messages'] == 1 || $userpower['speak'] == 1) {
  111. $time = time();
  112. $updateArr = [];
  113. if ($userpower['private_messages_time'] < $time) {
  114. $updateArr['private_messages'] = 0;
  115. $user->power->private_messages = 0;
  116. }
  117. if ($userpower['speak_time'] < $time) {
  118. $updateArr['speak'] = 0;
  119. $user->power->speak = 0;
  120. }
  121. if (!empty($updateArr)) {
  122. UserPower::where(['user_id'=>$user_id])->update($updateArr);
  123. }
  124. }*/
  125. $this->_user = $user;
  126. $this->_logined = true;
  127. $this->_token = $token;
  128. //初始化成功的事件
  129. Hook::listen("user_init_successed", $this->_user);
  130. return true;
  131. } else {
  132. $this->setError('You are not logged in');
  133. return false;
  134. }
  135. }
  136. /**
  137. * 注册用户
  138. *
  139. * @param string $username 用户名
  140. * @param string $password 密码
  141. * @param string $email 邮箱
  142. * @param string $mobile 手机号
  143. * @param array $extend 扩展参数
  144. * @return boolean
  145. */
  146. public function register($username, $password, $mobile = '', $extend = [])
  147. {
  148. // 检测用户名、昵称、手机号是否存在
  149. // if (User::getByUsername($username)) {
  150. // $this->setError('Username already exist');
  151. // return false;
  152. // }
  153. // if (User::getByNickname($username)) {
  154. // $this->setError('Nickname already exist');
  155. // return false;
  156. // }
  157. if (isset($extend['openid'])) {
  158. if (!empty($extend['openid']) && User::getByOpenid($extend['openid'])) {
  159. $this->setError('微信账号已存在');
  160. return false;
  161. }
  162. } else {
  163. if ($mobile && User::getByMobile($mobile)) {
  164. $this->setError('Mobile already exist');
  165. return false;
  166. }
  167. }
  168. $invite_no = User::column("invite_no");
  169. //用户id防重复
  170. $ids = User::column("u_id");
  171. $uidsale = Db::name('uidsale')->column('new_id');
  172. $uidsale_bag = Db::name('uidsale_bag')->column('u_id');
  173. $ids = array_merge($ids, $uidsale);
  174. $ids = array_merge($ids, $uidsale_bag);
  175. $ip = request()->ip();
  176. $time = time();
  177. $data = [
  178. 'u_id' => $this->getUinqueId(8, [$ids]),
  179. 'invite_no' => $this->getUinqueNo(8, $invite_no),
  180. // 'username' => $username,
  181. // 'password' => $password,
  182. 'mobile' => $mobile,
  183. 'level' => 0,
  184. 'score' => 0,
  185. 'avatar' => isset($extend["avatar"]) ? $extend["avatar"] : '/assets/img/default_avatar.png',
  186. 'image' => '/assets/img/default_avatar.png',
  187. //'desc' => '这个人很懒,什么都没留下~',
  188. ];
  189. if (isset($extend['openid']) && !empty($extend['openid'])) {
  190. $data['openid'] = $extend['openid'];
  191. }
  192. //https://bansheng-1304213176.cos.ap-guangzhou.myqcloud.com/
  193. $params = array_merge($data, [
  194. 'nickname' => get_rand_nick_name() . $data["u_id"],
  195. // 'salt' => Random::alnum(),
  196. 'joinip' => $ip,
  197. 'logintime' => $time,
  198. 'loginip' => $ip,
  199. 'status' => 1
  200. ]);
  201. // $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  202. $extend && $params = array_merge($params, $extend);
  203. //账号注册时需要开启事务,避免出现垃圾数据
  204. Db::startTrans();
  205. try {
  206. $user = User::create($params, true);
  207. $this->_user = User::get($user->id);
  208. $this->_user->username = 'u' . (10000 + $user->id);
  209. $this->_user->save();
  210. //设置Token
  211. $this->_token = Random::uuid();
  212. Token::set($this->_token, $user->id, $this->keeptime);
  213. //设置登录状态
  214. $this->_logined = true;
  215. $wallet_data = [
  216. 'user_id' => $user->id,
  217. ];
  218. //注册到钱包
  219. Db::name('user_wallet')->insertGetId($wallet_data);
  220. //注册用户活跃
  221. Db::name('user_active')->insertGetId($wallet_data);
  222. //注册到权限
  223. Db::name('user_power')->insertGetId($wallet_data);
  224. //完成任务,绑定手机号
  225. \app\common\model\TaskLog::tofinish($user->id,18);
  226. //初始化权限
  227. $userpower = UserPower::getByUserId($user->id);
  228. $this->_user->power = $userpower;
  229. //[环信]注册用户。忽略失败
  230. $easemob = new Easemob();
  231. $rs = $easemob->user_create($user->id);
  232. if($rs === false){
  233. $this->setError('注册用户失败');
  234. Db::rollback();
  235. return false;
  236. }
  237. //注册成功的事件
  238. Hook::listen("user_register_successed", $this->_user, $data);
  239. //\app\common\model\NewBagHave::insert(["user_id" => $user->id, "createtime" => time()]);
  240. Db::commit();
  241. } catch (Exception $e) {
  242. $this->setError($e->getMessage());
  243. Db::rollback();
  244. return false;
  245. }
  246. return true;
  247. }
  248. /**
  249. * 生成不重复的随机数字
  250. */
  251. function getUinqueId($length = 8, $ids = [])
  252. {
  253. $newid = Random::build("nozero", $length);
  254. if (in_array($newid, $ids)) {
  255. $newid = $this->getUinqueId($length, $ids);
  256. }
  257. return $newid;
  258. }
  259. /**
  260. * 生成不重复的随机数字字母组合
  261. */
  262. function getUinqueNo($length = 8, $nos = [])
  263. {
  264. $newid = Random::build("alnum", $length);
  265. if (in_array($newid, $nos)) {
  266. $newid = $this->getUinqueNo($length, $nos);
  267. }
  268. return $newid;
  269. }
  270. /**
  271. * 用户登录
  272. *
  273. * @param string $account 账号,用户名、邮箱、手机号
  274. * @param string $password 密码
  275. * @return boolean
  276. */
  277. public function login($account, $password)
  278. {
  279. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  280. $user = User::get([$field => $account]);
  281. if (!$user) {
  282. $this->setError('Account is incorrect');
  283. return false;
  284. }
  285. if ($user->status != 'normal') {
  286. $this->setError('Account is locked');
  287. return false;
  288. }
  289. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  290. $this->setError('Password is incorrect');
  291. return false;
  292. }
  293. //直接登录会员
  294. $this->direct($user->id);
  295. return true;
  296. }
  297. /**
  298. * 退出
  299. *
  300. * @return boolean
  301. */
  302. public function logout()
  303. {
  304. if (!$this->_logined) {
  305. $this->setError('You are not logged in');
  306. return false;
  307. }
  308. //设置登录标识
  309. $this->_logined = false;
  310. //删除Token
  311. Token::delete($this->_token);
  312. //退出成功的事件
  313. Hook::listen("user_logout_successed", $this->_user);
  314. return true;
  315. }
  316. /**
  317. * 修改密码
  318. * @param string $newpassword 新密码
  319. * @param string $oldpassword 旧密码
  320. * @param bool $ignoreoldpassword 忽略旧密码
  321. * @return boolean
  322. */
  323. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  324. {
  325. if (!$this->_logined) {
  326. $this->setError('You are not logged in');
  327. return false;
  328. }
  329. //判断旧密码是否正确
  330. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  331. Db::startTrans();
  332. try {
  333. $salt = Random::alnum();
  334. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  335. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  336. // Token::delete($this->_token);
  337. // //修改密码成功的事件
  338. // Hook::listen("user_changepwd_successed", $this->_user);
  339. Db::commit();
  340. } catch (Exception $e) {
  341. Db::rollback();
  342. $this->setError($e->getMessage());
  343. return false;
  344. }
  345. return true;
  346. } else {
  347. $this->setError('Password is incorrect');
  348. return false;
  349. }
  350. }
  351. /**
  352. * 直接登录账号
  353. * @param int $user_id
  354. * @return boolean
  355. */
  356. public function direct($user_id)
  357. {
  358. $user = User::getById($user_id);
  359. if ($user) {
  360. $userpower = UserPower::getByUserId($user_id);
  361. if(!$userpower){
  362. return false;
  363. }
  364. //这个项目没用到user_power的禁言
  365. /*if ($userpower['private_messages'] == 1 || $userpower['speak'] == 1) {
  366. $time = time();
  367. $updateArr = [];
  368. if ($userpower['private_messages_time'] < $time) {
  369. $updateArr['private_messages'] = 0;
  370. }
  371. if ($userpower['speak_time'] < $time) {
  372. $updateArr['speak_time'] = 0;
  373. }
  374. if (!empty($updateArr)) {
  375. UserPower::where(['user_id'=>$user_id])->update($updateArr);
  376. }
  377. }*/
  378. Db::startTrans();
  379. try {
  380. // 微信内置浏览器时不请空用户的token,APP才清除所有token
  381. if (!strpos($_SERVER["HTTP_USER_AGENT"], "MicroMessenger")) {
  382. // 先清除所有token
  383. Token::clear($user->id);
  384. }
  385. //$user->ipaddress = newip_to_address();
  386. $ip = request()->ip();
  387. $time = time();
  388. //记录本次登录的IP和时间
  389. $user->loginip = $ip;
  390. $user->logintime = $time;
  391. $user->save();
  392. $user->power = $userpower;// 追加权限
  393. $this->_user = $user;
  394. $this->_token = Random::uuid();
  395. Token::set($this->_token, $user->id, $this->keeptime);
  396. $this->_logined = true;
  397. //登录成功的事件
  398. Hook::listen("user_login_successed", $this->_user);
  399. Db::commit();
  400. } catch (Exception $e) {
  401. Db::rollback();
  402. $this->setError($e->getMessage());
  403. return false;
  404. }
  405. return true;
  406. } else {
  407. return false;
  408. }
  409. }
  410. /**
  411. * 检测是否是否有对应权限
  412. * @param string $path 控制器/方法
  413. * @param string $module 模块 默认为当前模块
  414. * @return boolean
  415. */
  416. public function check($path = null, $module = null)
  417. {
  418. if (!$this->_logined) {
  419. return false;
  420. }
  421. $ruleList = $this->getRuleList();
  422. $rules = [];
  423. foreach ($ruleList as $k => $v) {
  424. $rules[] = $v['name'];
  425. }
  426. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  427. $url = strtolower(str_replace('.', '/', $url));
  428. return in_array($url, $rules) ? true : false;
  429. }
  430. /**
  431. * 判断是否登录
  432. * @return boolean
  433. */
  434. public function isLogin()
  435. {
  436. if ($this->_logined) {
  437. return true;
  438. }
  439. return false;
  440. }
  441. /**
  442. * 获取当前Token
  443. * @return string
  444. */
  445. public function getToken()
  446. {
  447. return $this->_token;
  448. }
  449. /**
  450. * 获取会员基本信息
  451. */
  452. public function getUserinfo()
  453. {
  454. $data = $this->_user->toArray();
  455. $allowFields = $this->getAllowFields();
  456. $userinfo = array_intersect_key($data, array_flip($allowFields));
  457. $userinfo = array_merge($userinfo, Token::get($this->_token));
  458. //用户钱包
  459. $userwallet = Db::name('user_wallet')->where('user_id',$this->_user->id)->find();
  460. $userinfo['wallet'] = $userwallet;
  461. //关注数量
  462. $userinfo['follow_num'] = Db::name('user_follow')->where('uid',$this->id)->count('id');
  463. //粉丝数量
  464. $userinfo['fans_num'] = Db::name('user_follow')->where('follow_uid',$this->id)->count('id');
  465. //装扮
  466. $usercar = "";
  467. $userheader = "";
  468. // 获取用户头像框信息
  469. $map = [
  470. 'a.user_id' => $this->id,
  471. 'a.is_using' => 1,
  472. 'a.end_time' => ['gt',time()],
  473. ];
  474. $backResult = Db::name('user_decorate')->alias('a')
  475. ->field('a.id,a.decorate_type,b.base_image,b.play_image')
  476. ->join('decorate b', 'a.decorate_id = b.id')
  477. ->where($map)->order('a.id desc')->select();
  478. $backResult = list_domain_image($backResult,['base_image','play_image']);
  479. if ($backResult) {
  480. foreach ($backResult as $k => $v) {
  481. $v['decorate_type'] == 1 && $usercar = $v['play_image'];
  482. $v['decorate_type'] == 2 && $userheader = $v['play_image'];
  483. }
  484. }
  485. //装扮
  486. $userinfo["usercar"] = $usercar;
  487. $userinfo["userheader"] = $userheader;
  488. //
  489. $userField = 'id';
  490. $user = model('User')->field($userField)->where(["id" => $this->_user->id])->with(['useralipay','userbank','userauth'])->find();
  491. $userInfoA = model('User')->getAppendData($userinfo);
  492. $userinfo['age_text'] = $userInfoA['age_text'];
  493. $userinfo['province_text'] = $userInfoA['province_text'];
  494. $userinfo['city_text'] = $userInfoA['city_text'];
  495. $userinfo['job_text'] = $userInfoA['job_text'];
  496. $userinfo['friends_num'] = $userInfoA['friends_num'];
  497. $userinfo['look_num'] = $userInfoA['look_num'];
  498. // 是否设置密码
  499. $userinfo['is_setpwd'] = $data['password'] ? 1 : 0;
  500. //
  501. $userAlipay = isset($user['useralipay']) ? $user['useralipay'] : [];
  502. $userBank = isset($user['userbank']) ? $user['userbank'] : [];
  503. $userinfo['realname'] = isset($user['userauth']['realname']) ? $user['userauth']['realname'] : '';
  504. $userinfo['idcard'] = isset($user['userauth']['idcard']) ? $user['userauth']['idcard'] : '';
  505. $userinfo['bind_wechat'] = !empty($userinfo['openid']) ? 1 : 0;
  506. $userinfo['bind_alipay'] = !empty($userAlipay) ? 1 : 0;
  507. $userinfo['bind_bank'] = !empty($userBank) ? 1 : 0;
  508. //公会信息
  509. $guildField = 'g.id,g.g_id,g.user_id,g.party_id,g.name,g.image,g.desc,g.member,g.status';
  510. $guildWhere['gm.user_id'] = $this->_user->id;
  511. $guildWhere['g.status'] = 1;
  512. $guildInfo = model('Guild')->alias('g')->field($guildField)
  513. ->join('guild_member gm','gm.guild_id = g.id','LEFT')
  514. ->where($guildWhere)->order('id desc')->find();
  515. $userinfo['guild_info'] = !empty($guildInfo) ? $guildInfo : [];
  516. $guildStatus = -2;
  517. if (!empty($guildInfo)) {
  518. $guildStatus = (int)$guildInfo['status'];
  519. }
  520. $userinfo['guild_status'] = $guildStatus;//家族状态:公会状态:0=待审核,1=正常,-1=已解散,-2无公会
  521. //拥有的公会
  522. $userinfo['own_guild_id'] = 0;
  523. $own_guild_id = Db::name('guild')->where('user_id',$this->_user->id)->where('status',1)->value('id');
  524. if($own_guild_id){
  525. $userinfo['own_guild_id'] = $own_guild_id;
  526. }
  527. //
  528. /*if ($this->power->private_messages == 1 ||$this->power->speak == 1) {
  529. $time = time();
  530. $updateArr = [];
  531. if ($this->power->private_messages_time < $time) {
  532. $updateArr['private_messages'] = 0;
  533. $this->power->private_messages = 0;
  534. }
  535. if ($this->power->speak_time < $time) {
  536. $updateArr['speak_time'] = 0;
  537. $this->power->speak = 0;
  538. }
  539. if (!empty($updateArr)) {
  540. UserPower::where(['user_id'=>$this->_user->id])->update($updateArr);
  541. }
  542. }
  543. if (!isset($this->power)) {
  544. $userPowerWhere['user_id'] = $this->_user->id;
  545. $userPower = model('UserPower')->where($userPowerWhere)->find();
  546. } else {
  547. $userPower = $this->power;
  548. }
  549. $userinfo['user_power'] = $userPower;*/
  550. //魅力等级
  551. /*$charm_info = Db::name('user_config_charm')->where('level',$this->charm_level)->find();
  552. $userinfo['charm_image'] = localpath_to_netpath($charm_info['image']);
  553. $userinfo['charm_color'] = $charm_info['color'];*/
  554. //财富等级
  555. $wealth_info = Db::name('user_config_wealth')->where('level',$this->wealth_level)->find();
  556. $userinfo['wealth_image'] = localpath_to_netpath($wealth_info['image']);
  557. $userinfo['wealth_color'] = $wealth_info['color'];
  558. //
  559. return $userinfo;
  560. }
  561. /**
  562. * 获取会员组别规则列表
  563. * @return array
  564. */
  565. public function getRuleList()
  566. {
  567. if ($this->rules) {
  568. return $this->rules;
  569. }
  570. $group = $this->_user->group;
  571. if (!$group) {
  572. return [];
  573. }
  574. $rules = explode(',', $group->rules);
  575. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  576. return $this->rules;
  577. }
  578. /**
  579. * 获取当前请求的URI
  580. * @return string
  581. */
  582. public function getRequestUri()
  583. {
  584. return $this->requestUri;
  585. }
  586. /**
  587. * 设置当前请求的URI
  588. * @param string $uri
  589. */
  590. public function setRequestUri($uri)
  591. {
  592. $this->requestUri = $uri;
  593. }
  594. /**
  595. * 获取允许输出的字段
  596. * @return array
  597. */
  598. public function getAllowFields()
  599. {
  600. return $this->allowFields;
  601. }
  602. /**
  603. * 设置允许输出的字段
  604. * @param array $fields
  605. */
  606. public function setAllowFields($fields)
  607. {
  608. $this->allowFields = $fields;
  609. }
  610. /**
  611. * 删除一个指定会员
  612. * @param int $user_id 会员ID
  613. * @return boolean
  614. */
  615. public function delete($user_id)
  616. {
  617. $user = User::get($user_id);
  618. if (!$user) {
  619. return false;
  620. }
  621. Db::startTrans();
  622. try {
  623. // 删除会员
  624. User::destroy($user_id);
  625. // 删除会员指定的所有Token
  626. Token::clear($user_id);
  627. Hook::listen("user_delete_successed", $user);
  628. Db::commit();
  629. } catch (Exception $e) {
  630. Db::rollback();
  631. $this->setError($e->getMessage());
  632. return false;
  633. }
  634. return true;
  635. }
  636. /**
  637. * 获取密码加密后的字符串
  638. * @param string $password 密码
  639. * @param string $salt 密码盐
  640. * @return string
  641. */
  642. public function getEncryptPassword($password, $salt = '')
  643. {
  644. return md5(md5($password) . $salt);
  645. }
  646. /**
  647. * 检测当前控制器和方法是否匹配传递的数组
  648. *
  649. * @param array $arr 需要验证权限的数组
  650. * @return boolean
  651. */
  652. public function match($arr = [])
  653. {
  654. $request = Request::instance();
  655. $arr = is_array($arr) ? $arr : explode(',', $arr);
  656. if (!$arr) {
  657. return false;
  658. }
  659. $arr = array_map('strtolower', $arr);
  660. // 是否存在
  661. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  662. return true;
  663. }
  664. // 没找到匹配
  665. return false;
  666. }
  667. /**
  668. * 设置会话有效时间
  669. * @param int $keeptime 默认为永久
  670. */
  671. public function keeptime($keeptime = 0)
  672. {
  673. $this->keeptime = $keeptime;
  674. }
  675. /**
  676. * 渲染用户数据
  677. * @param array $datalist 二维数组
  678. * @param mixed $fields 加载的字段列表
  679. * @param string $fieldkey 渲染的字段
  680. * @param string $renderkey 结果字段
  681. * @return array
  682. */
  683. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  684. {
  685. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  686. $ids = [];
  687. foreach ($datalist as $k => $v) {
  688. if (!isset($v[$fieldkey])) {
  689. continue;
  690. }
  691. $ids[] = $v[$fieldkey];
  692. }
  693. $list = [];
  694. if ($ids) {
  695. if (!in_array('id', $fields)) {
  696. $fields[] = 'id';
  697. }
  698. $ids = array_unique($ids);
  699. $selectlist = User::where('id', 'in', $ids)->column($fields);
  700. foreach ($selectlist as $k => $v) {
  701. $list[$v['id']] = $v;
  702. }
  703. }
  704. foreach ($datalist as $k => &$v) {
  705. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  706. }
  707. unset($v);
  708. return $datalist;
  709. }
  710. /**
  711. * 设置错误信息
  712. *
  713. * @param $error 错误信息
  714. * @return Auth
  715. */
  716. public function setError($error)
  717. {
  718. $this->_error = $error;
  719. return $this;
  720. }
  721. /**
  722. * 获取错误信息
  723. * @return string
  724. */
  725. public function getError()
  726. {
  727. return $this->_error ? __($this->_error) : '';
  728. }
  729. }