Auth.php 29 KB

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