Auth.php 29 KB

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