Auth.php 26 KB

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