Auth.php 26 KB

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