Auth.php 29 KB

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