Auth.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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,is_stealth,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. $userinfo['is_stealth'] = isset($user['is_stealth']) ? $user['is_stealth'] : 0;
  477. //家族信息
  478. $guildField = 'g.id,g.g_id,g.user_id,g.party_id,g.name,g.image,g.desc,g.member,g.status';
  479. $guildWhere['gm.user_id'] = $this->_user->id;
  480. $guildWhere['g.status'] = 1;
  481. $guildInfo = model('Guild')->alias('g')->field($guildField)
  482. ->join('guild_member gm','gm.guild_id = g.id','LEFT')
  483. ->where($guildWhere)->order('id desc')->find();
  484. $userinfo['guild_info'] = !empty($guildInfo) ? $guildInfo : [];
  485. $guildStatus = -2;
  486. if (!empty($guildInfo)) {
  487. $guildStatus = (int)$guildInfo['status'];
  488. }
  489. $userinfo['guild_status'] = $guildStatus;//家族状态:公会状态:0=待审核,1=正常,-1=已解散,-2无公会
  490. //消费额是否能开箱子和大转盘
  491. $userinfo['can_egggift'] = 0;
  492. $where = [];
  493. $where["user_id"] = $this->_user->id;
  494. $where["mode"] = '-';//查看wallet.php文件
  495. $jewel_sum = Db::name('user_jewel_log')->where($where)->sum('value');
  496. $eggplay_paymoney_min = config('site.eggplay_paymoney_min');
  497. if($jewel_sum >= $eggplay_paymoney_min){
  498. $userinfo['can_egggift'] = 1;
  499. }
  500. //拥有的家族
  501. $userinfo['own_guild_id'] = 0;
  502. $own_guild_id = Db::name('guild')->where('user_id',$this->_user->id)->where('status',1)->value('id');
  503. if($own_guild_id){
  504. $userinfo['own_guild_id'] = $own_guild_id;
  505. }
  506. if ($this->power->private_messages == 1 ||$this->power->speak == 1) {
  507. $time = time();
  508. $updateArr = [];
  509. if ($this->power->private_messages_time < $time) {
  510. $updateArr['private_messages'] = 0;
  511. $this->power->private_messages = 0;
  512. }
  513. if ($this->power->speak_time < $time) {
  514. $updateArr['speak_time'] = 0;
  515. $this->power->speak = 0;
  516. }
  517. if (!empty($updateArr)) {
  518. UserPower::where(['user_id'=>$this->_user->id])->update($updateArr);
  519. }
  520. }
  521. $userinfo['user_power'] = $this->power;
  522. $userinfo['pre_nickname'] = isset($user['pre_nickname']) ? $user['pre_nickname'] : '';
  523. $userinfo['pre_avatar'] = isset($user['pre_avatar']) ? $user['pre_avatar'] : '';
  524. $userinfo['nickname_status'] = $userinfo['avatar_status'] = 0;
  525. if (!empty($user['pre_nickname']) && $user['pre_nickname'] != $user['nickname']) {
  526. $userinfo['nickname_status'] = 1;
  527. }
  528. if (!empty($user['pre_avatar']) && $user['pre_avatar'] != $user['avatar']) {
  529. $userinfo['avatar_status'] = 1;
  530. }
  531. //
  532. return $userinfo;
  533. }
  534. /**
  535. * 获取会员组别规则列表
  536. * @return array
  537. */
  538. public function getRuleList()
  539. {
  540. if ($this->rules) {
  541. return $this->rules;
  542. }
  543. $group = $this->_user->group;
  544. if (!$group) {
  545. return [];
  546. }
  547. $rules = explode(',', $group->rules);
  548. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  549. return $this->rules;
  550. }
  551. /**
  552. * 获取当前请求的URI
  553. * @return string
  554. */
  555. public function getRequestUri()
  556. {
  557. return $this->requestUri;
  558. }
  559. /**
  560. * 设置当前请求的URI
  561. * @param string $uri
  562. */
  563. public function setRequestUri($uri)
  564. {
  565. $this->requestUri = $uri;
  566. }
  567. /**
  568. * 获取允许输出的字段
  569. * @return array
  570. */
  571. public function getAllowFields()
  572. {
  573. return $this->allowFields;
  574. }
  575. /**
  576. * 设置允许输出的字段
  577. * @param array $fields
  578. */
  579. public function setAllowFields($fields)
  580. {
  581. $this->allowFields = $fields;
  582. }
  583. /**
  584. * 删除一个指定会员
  585. * @param int $user_id 会员ID
  586. * @return boolean
  587. */
  588. public function delete($user_id)
  589. {
  590. $user = User::get($user_id);
  591. if (!$user) {
  592. return false;
  593. }
  594. Db::startTrans();
  595. try {
  596. // 删除会员
  597. User::destroy($user_id);
  598. // 删除会员指定的所有Token
  599. Token::clear($user_id);
  600. Hook::listen("user_delete_successed", $user);
  601. Db::commit();
  602. } catch (Exception $e) {
  603. Db::rollback();
  604. $this->setError($e->getMessage());
  605. return false;
  606. }
  607. return true;
  608. }
  609. /**
  610. * 获取密码加密后的字符串
  611. * @param string $password 密码
  612. * @param string $salt 密码盐
  613. * @return string
  614. */
  615. public function getEncryptPassword($password, $salt = '')
  616. {
  617. return md5(md5($password) . $salt);
  618. }
  619. /**
  620. * 检测当前控制器和方法是否匹配传递的数组
  621. *
  622. * @param array $arr 需要验证权限的数组
  623. * @return boolean
  624. */
  625. public function match($arr = [])
  626. {
  627. $request = Request::instance();
  628. $arr = is_array($arr) ? $arr : explode(',', $arr);
  629. if (!$arr) {
  630. return false;
  631. }
  632. $arr = array_map('strtolower', $arr);
  633. // 是否存在
  634. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  635. return true;
  636. }
  637. // 没找到匹配
  638. return false;
  639. }
  640. /**
  641. * 设置会话有效时间
  642. * @param int $keeptime 默认为永久
  643. */
  644. public function keeptime($keeptime = 0)
  645. {
  646. $this->keeptime = $keeptime;
  647. }
  648. /**
  649. * 渲染用户数据
  650. * @param array $datalist 二维数组
  651. * @param mixed $fields 加载的字段列表
  652. * @param string $fieldkey 渲染的字段
  653. * @param string $renderkey 结果字段
  654. * @return array
  655. */
  656. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  657. {
  658. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  659. $ids = [];
  660. foreach ($datalist as $k => $v) {
  661. if (!isset($v[$fieldkey])) {
  662. continue;
  663. }
  664. $ids[] = $v[$fieldkey];
  665. }
  666. $list = [];
  667. if ($ids) {
  668. if (!in_array('id', $fields)) {
  669. $fields[] = 'id';
  670. }
  671. $ids = array_unique($ids);
  672. $selectlist = User::where('id', 'in', $ids)->column($fields);
  673. foreach ($selectlist as $k => $v) {
  674. $list[$v['id']] = $v;
  675. }
  676. }
  677. foreach ($datalist as $k => &$v) {
  678. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  679. }
  680. unset($v);
  681. return $datalist;
  682. }
  683. /**
  684. * 设置错误信息
  685. *
  686. * @param $error 错误信息
  687. * @return Auth
  688. */
  689. public function setError($error)
  690. {
  691. $this->_error = $error;
  692. return $this;
  693. }
  694. /**
  695. * 获取错误信息
  696. * @return string
  697. */
  698. public function getError()
  699. {
  700. return $this->_error ? __($this->_error) : '';
  701. }
  702. public function openid_register($wechat_openid = '', $extend = [])
  703. {
  704. if ($wechat_openid && User::getByOpenid($wechat_openid)) {
  705. $this->setError('openid已存在');
  706. return false;
  707. }
  708. $ip = request()->ip();
  709. $time = time();
  710. $introcode = User::column("invite_no");
  711. $data = [
  712. 'wechat_openid' => $wechat_openid,
  713. 'gender' => isset($extend['gender']) ? $extend['gender'] : 1,
  714. 'avatar' => isset($extend["avatar"]) ? $extend["avatar"] : '/assets/dc0f37f043e1e9f5240ed87e37f18740.png',
  715. 'invite_no' => $this->getUinqueNo(6, $introcode),
  716. 'nickname' => get_rand_nick_name(),
  717. ];
  718. $params = array_merge($data, [
  719. 'salt' => Random::alnum(),
  720. 'jointime' => $time,
  721. 'joinip' => $ip,
  722. 'logintime' => $time,
  723. 'loginip' => $ip,
  724. 'prevtime' => $time,
  725. 'status' => 'normal'
  726. ]);
  727. $params = array_merge($params, $extend);
  728. //账号注册时需要开启事务,避免出现垃圾数据
  729. Db::startTrans();
  730. try {
  731. $user = User::create($params, true);
  732. $this->_user = User::get($user->id);
  733. $this->_user->u_id = $this->getUinqueId(8, [$user->id]);
  734. $this->_user->save();
  735. //设置Token
  736. $this->_token = Random::uuid();
  737. Token::set($this->_token, $user->id, $this->keeptime);
  738. //设置登录状态
  739. $this->_logined = true;
  740. //初始化权限
  741. $userPowerWhere['user_id'] = $user->id;
  742. $userPowerData = Db::name('user_power')->where($userPowerWhere)->find();
  743. if (empty($userPowerData)) {
  744. $powerData = ['user_id' => $user->id];
  745. Db::name('user_power')->insertGetId($powerData);
  746. }
  747. //注册成功的事件
  748. Hook::listen("user_register_successed", $this->_user, $data);
  749. \app\common\model\NewBagHave::insert(["user_id" => $user->id, "createtime" => time()]);
  750. Db::commit();
  751. } catch (Exception $e) {echo '<pre>';var_dump($e->getLine());exit;
  752. $this->setError($e->getMessage());
  753. Db::rollback();
  754. return false;
  755. }
  756. return true;
  757. }
  758. }