Auth.php 26 KB

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