Auth.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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. $ids = User::column("u_id");
  168. $invite_no = User::column("invite_no");
  169. $uidsale = config("site.uidsale");
  170. $uidsale = explode(",", $uidsale);
  171. if (is_array($uidsale) && $uidsale && $ids) $ids = array_merge($ids, $uidsale);
  172. $ip = request()->ip();
  173. $time = time();
  174. $data = [
  175. 'u_id' => $this->getUinqueId(8, [$ids]),
  176. 'invite_no' => $this->getUinqueNo(8, $invite_no),
  177. 'username' => $username,
  178. // 'password' => $password,
  179. 'mobile' => $mobile,
  180. 'level' => 0,
  181. 'score' => 0,
  182. 'avatar' => isset($extend["avatar"]) ? $extend["avatar"] : '/assets/img/default_avatar.png',
  183. 'image' => '/assets/img/default_avatar.png',
  184. //'desc' => '这个人很懒,什么都没留下~',
  185. ];
  186. if (isset($extend['openid']) && !empty($extend['openid'])) {
  187. $data['openid'] = $extend['openid'];
  188. }
  189. //https://bansheng-1304213176.cos.ap-guangzhou.myqcloud.com/
  190. $params = array_merge($data, [
  191. 'nickname' => "gg_" . $data["u_id"],
  192. 'salt' => Random::alnum(),
  193. 'joinip' => $ip,
  194. 'logintime' => $time,
  195. 'loginip' => $ip,
  196. 'status' => 'normal'
  197. ]);
  198. // $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  199. $extend && $params = array_merge($params, $extend);
  200. //账号注册时需要开启事务,避免出现垃圾数据
  201. Db::startTrans();
  202. try {
  203. $user = User::create($params, true);
  204. $this->_user = User::get($user->id);
  205. //设置Token
  206. $this->_token = Random::uuid();
  207. Token::set($this->_token, $user->id, $this->keeptime);
  208. //设置登录状态
  209. $this->_logined = true;
  210. //初始化权限
  211. $userPowerWhere['user_id'] = $user->id;
  212. $userPowerData = Db::name('user_power')->where($userPowerWhere)->find();
  213. if (empty($userPowerData)) {
  214. $powerData = ['user_id' => $user->id];
  215. Db::name('user_power')->insertGetId($powerData);
  216. }
  217. $userpower = UserPower::getByUserId($user->id);
  218. $this->_user->power = $userpower;
  219. //注册到钱包
  220. $wallet_data = [
  221. 'user_id' => $user->id,
  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. //用户钱包
  449. $userwallet = Db::name('user_wallet')->where('user_id',$this->_user->id)->find();
  450. $userinfo['money'] = $userwallet['money'];
  451. $userinfo['jewel'] = $userwallet['jewel'];
  452. $userinfo = array_merge($userinfo, Token::get($this->_token));
  453. $userinfo = array_merge($userinfo, $fansfollows);
  454. // 获取贵族信息
  455. $nobleInfo = $this->_user->getUserNobleInfo($this->_user->id);
  456. $userinfo = array_merge($userinfo, $nobleInfo);
  457. $usercar = "";
  458. $userheader = "";
  459. $userlight = "";
  460. $userpop = "";
  461. $userandroidpop = "";
  462. // 获取用户头像框和座驾信息
  463. $backResult = \app\common\model\AttireBack::field("file_image,gif_image,type,android_image")
  464. ->where(["user_id" => $this->_user->id, "is_using" => 1, "is_use" => 1, "duetime" => ["gt", time()]])->select();
  465. if ($backResult) {
  466. foreach ($backResult as $k => $v) {
  467. $v["type"] == 1 && $usercar = $v["gif_image"];
  468. $v["type"] == 2 && $userheader = $v["gif_image"];
  469. $v["type"] == 3 && $userlight = $v["file_image"];
  470. $v["type"] == 4 && $userpop = $v["file_image"];
  471. $v["type"] == 4 && $userandroidpop = $v["android_image"];
  472. }
  473. }
  474. $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';
  475. $user = model('User')->field($userField)->where(["id" => $this->_user->id])->with(['useralipay','userbank','userauth'])->find();
  476. // 获取我的推荐人的邀请码
  477. $preUserField = 'id,invite_no';
  478. $preUser = model('User')->field($preUserField)->where(["id" => $this->_user->pre_userid])->find();
  479. $preCode = isset($preUser['invite_no']) ? $preUser['invite_no'] : '';
  480. $userinfo["preCode"] = $preCode;
  481. $userinfo["usercar"] = $usercar;
  482. $userinfo["userheader"] = $userheader;
  483. $userinfo["userlight"] = $userlight;
  484. $userinfo["userpop"] = $userpop;
  485. $userinfo["userandroidpop"] = $userandroidpop;
  486. $userInfoA = model('User')->getAppendData($userinfo);
  487. $userInfo['age_text'] = $userInfoA['age_text'];
  488. $userInfo['constellation_text'] = $userInfoA['constellation_text'];
  489. $userInfo['province_text'] = $userInfoA['province_text'];
  490. $userInfo['city_text'] = $userInfoA['city_text'];
  491. $userInfo['friends_num'] = $userInfoA['friends_num'];
  492. $userInfo['look_num'] = $userInfoA['look_num'];
  493. // 是否设置密码
  494. $userinfo['is_setpwd'] = $data['password'] ? 1 : 0;
  495. $field = 'id,age_id,constellation_id,province_id,city_id,desc';
  496. $fieldArr = explode(',',$field);
  497. $fieldTextArr = ['age_text','constellation_text','province_text','city_text','friends_num','look_num'];
  498. $fieldArr = array_merge($fieldArr,$fieldTextArr);
  499. //$userData = model('User')->field($field)->with(['userauth'])->where(['id'=>$this->_user->id])->find();
  500. foreach ($fieldArr as $key => $value) {
  501. $userinfo[$value] = isset($user[$value]) ? $user[$value] : '';
  502. }
  503. $userAlipay = isset($user['useralipay']) ? $user['useralipay'] : [];
  504. $userBank = isset($user['userbank']) ? $user['userbank'] : [];
  505. $userinfo['realname'] = isset($user['userauth']['realname']) ? $user['userauth']['realname'] : '';
  506. $userinfo['idcard'] = isset($user['userauth']['idcard']) ? $user['userauth']['idcard'] : '';
  507. $userinfo['is_pay_pwd'] = !empty($user['pay_password']) ? 1 : 0;
  508. $userinfo['bind_wechat'] = !empty($user['openid']) ? 1 : 0;
  509. $userinfo['bind_alipay'] = !empty($userAlipay) ? 1 : 0;
  510. $userinfo['bind_bank'] = !empty($userBank) ? 1 : 0;
  511. $userinfo['is_cool'] = isset($user['is_cool']) ? $user['is_cool'] : 0;
  512. $userinfo['is_manager'] = isset($user['is_manager']) ? $user['is_manager'] : 0;
  513. $userinfo['is_stealth'] = isset($user['is_stealth']) ? $user['is_stealth'] : 0;
  514. //家族信息
  515. $guildField = 'g.id,g.g_id,g.user_id,g.party_id,g.name,g.image,g.desc,g.member,g.status';
  516. $guildWhere['gm.user_id'] = $this->_user->id;
  517. $guildWhere['g.status'] = 1;
  518. $guildInfo = model('Guild')->alias('g')->field($guildField)
  519. ->join('guild_member gm','gm.guild_id = g.id','LEFT')
  520. ->where($guildWhere)->order('id desc')->find();
  521. $userinfo['guild_info'] = !empty($guildInfo) ? $guildInfo : [];
  522. $guildStatus = -2;
  523. if (!empty($guildInfo)) {
  524. $guildStatus = (int)$guildInfo['status'];
  525. }
  526. $userinfo['guild_status'] = $guildStatus;//家族状态:公会状态:0=待审核,1=正常,-1=已解散,-2无公会
  527. //消费额是否能开箱子和大转盘
  528. $userinfo['can_egggift'] = 0;
  529. $where = [];
  530. $where["user_id"] = $this->_user->id;
  531. $where["mode"] = '-';//查看wallet.php文件
  532. $jewel_sum = Db::name('user_jewel_log')->where($where)->sum('value');
  533. $eggplay_paymoney_min = config('site.eggplay_paymoney_min');
  534. if($jewel_sum >= $eggplay_paymoney_min){
  535. $userinfo['can_egggift'] = 1;
  536. }
  537. //全局关闭
  538. if(config('site.eggnew_global_show') == 0){
  539. $userinfo['can_egggift'] = 0;
  540. }
  541. //拥有的家族
  542. $userinfo['own_guild_id'] = 0;
  543. $own_guild_id = Db::name('guild')->where('user_id',$this->_user->id)->where('status',1)->value('id');
  544. if($own_guild_id){
  545. $userinfo['own_guild_id'] = $own_guild_id;
  546. }
  547. if ($this->power->private_messages == 1 ||$this->power->speak == 1) {
  548. $time = time();
  549. $updateArr = [];
  550. if ($this->power->private_messages_time < $time) {
  551. $updateArr['private_messages'] = 0;
  552. $this->power->private_messages = 0;
  553. }
  554. if ($this->power->speak_time < $time) {
  555. $updateArr['speak_time'] = 0;
  556. $this->power->speak = 0;
  557. }
  558. if (!empty($updateArr)) {
  559. UserPower::where(['user_id'=>$this->_user->id])->update($updateArr);
  560. }
  561. }
  562. if (!isset($this->power)) {
  563. $userPowerWhere['user_id'] = $this->_user->id;
  564. $userPower = model('UserPower')->where($userPowerWhere)->find();
  565. } else {
  566. $userPower = $this->power;
  567. }
  568. $userinfo['user_power'] = $userPower;
  569. $userinfo['pre_nickname'] = isset($user['pre_nickname']) ? $user['pre_nickname'] : '';
  570. $userinfo['pre_avatar'] = isset($user['pre_avatar']) ? $user['pre_avatar'] : '';
  571. $userinfo['nickname_status'] = $userinfo['avatar_status'] = 0;
  572. if (!empty($user['pre_nickname']) && $user['pre_nickname'] != $user['nickname']) {
  573. $userinfo['nickname_status'] = 1;
  574. }
  575. if (!empty($user['pre_avatar']) && $user['pre_avatar'] != $user['avatar']) {
  576. $userinfo['avatar_status'] = 1;
  577. }
  578. //贡献等级
  579. $charm_info = Db::name('user_config_charm')->where('level',$this->charm_level)->find();
  580. $userinfo['charm_image'] = localpath_to_netpath($charm_info['image']);
  581. $userinfo['charm_color'] = $charm_info['color'];
  582. //财富等级
  583. $wealth_info = Db::name('user_config_wealth')->where('level',$this->wealth_level)->find();
  584. $userinfo['wealth_image'] = localpath_to_netpath($wealth_info['image']);
  585. $userinfo['wealth_color'] = $wealth_info['color'];
  586. //
  587. return $userinfo;
  588. }
  589. /**
  590. * 获取会员组别规则列表
  591. * @return array
  592. */
  593. public function getRuleList()
  594. {
  595. if ($this->rules) {
  596. return $this->rules;
  597. }
  598. $group = $this->_user->group;
  599. if (!$group) {
  600. return [];
  601. }
  602. $rules = explode(',', $group->rules);
  603. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  604. return $this->rules;
  605. }
  606. /**
  607. * 获取当前请求的URI
  608. * @return string
  609. */
  610. public function getRequestUri()
  611. {
  612. return $this->requestUri;
  613. }
  614. /**
  615. * 设置当前请求的URI
  616. * @param string $uri
  617. */
  618. public function setRequestUri($uri)
  619. {
  620. $this->requestUri = $uri;
  621. }
  622. /**
  623. * 获取允许输出的字段
  624. * @return array
  625. */
  626. public function getAllowFields()
  627. {
  628. return $this->allowFields;
  629. }
  630. /**
  631. * 设置允许输出的字段
  632. * @param array $fields
  633. */
  634. public function setAllowFields($fields)
  635. {
  636. $this->allowFields = $fields;
  637. }
  638. /**
  639. * 删除一个指定会员
  640. * @param int $user_id 会员ID
  641. * @return boolean
  642. */
  643. public function delete($user_id)
  644. {
  645. $user = User::get($user_id);
  646. if (!$user) {
  647. return false;
  648. }
  649. Db::startTrans();
  650. try {
  651. // 删除会员
  652. User::destroy($user_id);
  653. // 删除会员指定的所有Token
  654. Token::clear($user_id);
  655. Hook::listen("user_delete_successed", $user);
  656. Db::commit();
  657. } catch (Exception $e) {
  658. Db::rollback();
  659. $this->setError($e->getMessage());
  660. return false;
  661. }
  662. return true;
  663. }
  664. /**
  665. * 获取密码加密后的字符串
  666. * @param string $password 密码
  667. * @param string $salt 密码盐
  668. * @return string
  669. */
  670. public function getEncryptPassword($password, $salt = '')
  671. {
  672. return md5(md5($password) . $salt);
  673. }
  674. /**
  675. * 检测当前控制器和方法是否匹配传递的数组
  676. *
  677. * @param array $arr 需要验证权限的数组
  678. * @return boolean
  679. */
  680. public function match($arr = [])
  681. {
  682. $request = Request::instance();
  683. $arr = is_array($arr) ? $arr : explode(',', $arr);
  684. if (!$arr) {
  685. return false;
  686. }
  687. $arr = array_map('strtolower', $arr);
  688. // 是否存在
  689. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  690. return true;
  691. }
  692. // 没找到匹配
  693. return false;
  694. }
  695. /**
  696. * 设置会话有效时间
  697. * @param int $keeptime 默认为永久
  698. */
  699. public function keeptime($keeptime = 0)
  700. {
  701. $this->keeptime = $keeptime;
  702. }
  703. /**
  704. * 渲染用户数据
  705. * @param array $datalist 二维数组
  706. * @param mixed $fields 加载的字段列表
  707. * @param string $fieldkey 渲染的字段
  708. * @param string $renderkey 结果字段
  709. * @return array
  710. */
  711. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  712. {
  713. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  714. $ids = [];
  715. foreach ($datalist as $k => $v) {
  716. if (!isset($v[$fieldkey])) {
  717. continue;
  718. }
  719. $ids[] = $v[$fieldkey];
  720. }
  721. $list = [];
  722. if ($ids) {
  723. if (!in_array('id', $fields)) {
  724. $fields[] = 'id';
  725. }
  726. $ids = array_unique($ids);
  727. $selectlist = User::where('id', 'in', $ids)->column($fields);
  728. foreach ($selectlist as $k => $v) {
  729. $list[$v['id']] = $v;
  730. }
  731. }
  732. foreach ($datalist as $k => &$v) {
  733. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  734. }
  735. unset($v);
  736. return $datalist;
  737. }
  738. /**
  739. * 设置错误信息
  740. *
  741. * @param $error 错误信息
  742. * @return Auth
  743. */
  744. public function setError($error)
  745. {
  746. $this->_error = $error;
  747. return $this;
  748. }
  749. /**
  750. * 获取错误信息
  751. * @return string
  752. */
  753. public function getError()
  754. {
  755. return $this->_error ? __($this->_error) : '';
  756. }
  757. public function openid_register($wechat_openid = '', $extend = [])
  758. {
  759. if ($wechat_openid && User::getByOpenid($wechat_openid)) {
  760. $this->setError('openid已存在');
  761. return false;
  762. }
  763. $ip = request()->ip();
  764. $time = time();
  765. $introcode = User::column("invite_no");
  766. $data = [
  767. 'openid' => $wechat_openid,
  768. 'gender' => isset($extend['gender']) ? $extend['gender'] : 1,
  769. 'avatar' => isset($extend["avatar"]) ? $extend["avatar"] : '/assets/dc0f37f043e1e9f5240ed87e37f18740.png',
  770. 'invite_no' => $this->getUinqueNo(6, $introcode),
  771. 'nickname' => get_rand_nick_name(),
  772. ];
  773. $params = array_merge($data, [
  774. 'salt' => Random::alnum(),
  775. 'jointime' => $time,
  776. 'joinip' => $ip,
  777. 'logintime' => $time,
  778. 'loginip' => $ip,
  779. 'prevtime' => $time,
  780. 'status' => 'normal'
  781. ]);
  782. $params = array_merge($params, $extend);
  783. //账号注册时需要开启事务,避免出现垃圾数据
  784. Db::startTrans();
  785. try {
  786. $user = User::create($params, true);
  787. $this->_user = User::get($user->id);
  788. $this->_user->u_id = $this->getUinqueId(8, [$user->id]);
  789. $this->_user->save();
  790. //设置Token
  791. $this->_token = Random::uuid();
  792. Token::set($this->_token, $user->id, $this->keeptime);
  793. //设置登录状态
  794. $this->_logined = true;
  795. //初始化权限
  796. $userPowerWhere['user_id'] = $user->id;
  797. $userPowerData = Db::name('user_power')->where($userPowerWhere)->find();
  798. if (empty($userPowerData)) {
  799. $powerData = ['user_id' => $user->id];
  800. Db::name('user_power')->insertGetId($powerData);
  801. }
  802. //注册到钱包
  803. $wallet_data = [
  804. 'user_id' => $user->id,
  805. ];
  806. Db::name('user_wallet')->insertGetId($wallet_data);
  807. //注册成功的事件
  808. Hook::listen("user_register_successed", $this->_user, $data);
  809. \app\common\model\NewBagHave::insert(["user_id" => $user->id, "createtime" => time()]);
  810. Db::commit();
  811. } catch (Exception $e) {echo '<pre>';var_dump($e->getLine());exit;
  812. $this->setError($e->getMessage());
  813. Db::rollback();
  814. return false;
  815. }
  816. return true;
  817. }
  818. }