Auth.php 29 KB

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