Auth.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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_guild', 'guild_id', 'avatar', 'empirical', 'image','level', 'gender', 'age_id',
  29. 'wealth_level','charm_level',
  30. 'job_id', 'longitude', 'latitude','province_id','city_id'
  31. ];
  32. public function __construct($options = [])
  33. {
  34. if ($config = Config::get('user')) {
  35. $this->config = array_merge($this->config, $config);
  36. }
  37. $this->options = array_merge($this->config, $options);
  38. }
  39. /**
  40. *
  41. * @param array $options 参数
  42. * @return Auth
  43. */
  44. public static function instance($options = [])
  45. {
  46. if (is_null(self::$instance)) {
  47. self::$instance = new static($options);
  48. }
  49. return self::$instance;
  50. }
  51. /**
  52. * 获取User模型
  53. * @return User
  54. */
  55. public function getUser()
  56. {
  57. return $this->_user;
  58. }
  59. /**
  60. * 兼容调用user模型的属性
  61. *
  62. * @param string $name
  63. * @return mixed
  64. */
  65. public function __get($name)
  66. {
  67. return $this->_user ? $this->_user->$name : null;
  68. }
  69. /**
  70. * 根据Token初始化
  71. *
  72. * @param string $token Token
  73. * @return boolean
  74. */
  75. public function init($token)
  76. {
  77. if ($this->_logined) {
  78. return true;
  79. }
  80. if ($this->_error) {
  81. return false;
  82. }
  83. $data = Token::get($token);
  84. if (!$data) {
  85. return false;
  86. }
  87. $user_id = intval($data['user_id']);
  88. if ($user_id > 0) {
  89. $user = User::get($user_id);
  90. if (!$user) {
  91. $this->setError('Account not exist');
  92. return false;
  93. }
  94. if ($user['status'] == -1) {
  95. $this->setError('账号已注销');
  96. return false;
  97. }
  98. if ($user['status'] != 1) {
  99. $this->setError('Account is locked');
  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' => get_rand_nick_name() . $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. $easemob = new Easemob();
  223. $rs = $easemob->user_create($user->id);
  224. if($rs === false){
  225. $this->setError('注册用户失败');
  226. Db::rollback();
  227. return false;
  228. }
  229. //注册成功的事件
  230. Hook::listen("user_register_successed", $this->_user, $data);
  231. \app\common\model\NewBagHave::insert(["user_id" => $user->id, "createtime" => time()]);
  232. Db::commit();
  233. } catch (Exception $e) {
  234. $this->setError($e->getMessage());
  235. Db::rollback();
  236. return false;
  237. }
  238. return true;
  239. }
  240. /**
  241. * 生成不重复的随机数字
  242. */
  243. function getUinqueId($length = 8, $ids = [])
  244. {
  245. $newid = Random::build("nozero", $length);
  246. if (in_array($newid, $ids)) {
  247. $newid = $this->getUinqueId($length, $ids);
  248. }
  249. return $newid;
  250. }
  251. /**
  252. * 生成不重复的随机数字字母组合
  253. */
  254. function getUinqueNo($length = 8, $nos = [])
  255. {
  256. $newid = Random::build("alnum", $length);
  257. if (in_array($newid, $nos)) {
  258. $newid = $this->getUinqueNo($length, $nos);
  259. }
  260. return $newid;
  261. }
  262. /**
  263. * 用户登录
  264. *
  265. * @param string $account 账号,用户名、邮箱、手机号
  266. * @param string $password 密码
  267. * @return boolean
  268. */
  269. public function login($account, $password)
  270. {
  271. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  272. $user = User::get([$field => $account]);
  273. if (!$user) {
  274. $this->setError('Account is incorrect');
  275. return false;
  276. }
  277. if ($user->status != 'normal') {
  278. $this->setError('Account is locked');
  279. return false;
  280. }
  281. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  282. $this->setError('Password is incorrect');
  283. return false;
  284. }
  285. //直接登录会员
  286. $this->direct($user->id);
  287. return true;
  288. }
  289. /**
  290. * 退出
  291. *
  292. * @return boolean
  293. */
  294. public function logout()
  295. {
  296. if (!$this->_logined) {
  297. $this->setError('You are not logged in');
  298. return false;
  299. }
  300. //设置登录标识
  301. $this->_logined = false;
  302. //删除Token
  303. Token::delete($this->_token);
  304. //退出成功的事件
  305. Hook::listen("user_logout_successed", $this->_user);
  306. return true;
  307. }
  308. /**
  309. * 修改密码
  310. * @param string $newpassword 新密码
  311. * @param string $oldpassword 旧密码
  312. * @param bool $ignoreoldpassword 忽略旧密码
  313. * @return boolean
  314. */
  315. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  316. {
  317. if (!$this->_logined) {
  318. $this->setError('You are not logged in');
  319. return false;
  320. }
  321. //判断旧密码是否正确
  322. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  323. Db::startTrans();
  324. try {
  325. $salt = Random::alnum();
  326. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  327. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  328. // Token::delete($this->_token);
  329. // //修改密码成功的事件
  330. // Hook::listen("user_changepwd_successed", $this->_user);
  331. Db::commit();
  332. } catch (Exception $e) {
  333. Db::rollback();
  334. $this->setError($e->getMessage());
  335. return false;
  336. }
  337. return true;
  338. } else {
  339. $this->setError('Password is incorrect');
  340. return false;
  341. }
  342. }
  343. /**
  344. * 直接登录账号
  345. * @param int $user_id
  346. * @return boolean
  347. */
  348. public function direct($user_id)
  349. {
  350. $user = User::getById($user_id);
  351. if ($user) {
  352. $userpower = UserPower::getByUserId($user_id);
  353. if(!$userpower){
  354. return false;
  355. }
  356. if ($userpower['private_messages'] == 1 || $userpower['speak'] == 1) {
  357. $time = time();
  358. $updateArr = [];
  359. if ($userpower['private_messages_time'] < $time) {
  360. $updateArr['private_messages'] = 0;
  361. }
  362. if ($userpower['speak_time'] < $time) {
  363. $updateArr['speak_time'] = 0;
  364. }
  365. if (!empty($updateArr)) {
  366. UserPower::where(['user_id'=>$user_id])->update($updateArr);
  367. }
  368. }
  369. Db::startTrans();
  370. try {
  371. // 微信内置浏览器时不请空用户的token,APP才清除所有token
  372. if (!strpos($_SERVER["HTTP_USER_AGENT"], "MicroMessenger")) {
  373. // 先清除所有token
  374. Token::clear($user->id);
  375. }
  376. //$user->ipaddress = newip_to_address();
  377. $ip = request()->ip();
  378. $time = time();
  379. //记录本次登录的IP和时间
  380. $user->loginip = $ip;
  381. $user->logintime = $time;
  382. $user->save();
  383. $user->power = $userpower;// 追加权限
  384. $this->_user = $user;
  385. $this->_token = Random::uuid();
  386. Token::set($this->_token, $user->id, $this->keeptime);
  387. $this->_logined = true;
  388. //登录成功的事件
  389. Hook::listen("user_login_successed", $this->_user);
  390. Db::commit();
  391. } catch (Exception $e) {
  392. Db::rollback();
  393. $this->setError($e->getMessage());
  394. return false;
  395. }
  396. return true;
  397. } else {
  398. return false;
  399. }
  400. }
  401. /**
  402. * 检测是否是否有对应权限
  403. * @param string $path 控制器/方法
  404. * @param string $module 模块 默认为当前模块
  405. * @return boolean
  406. */
  407. public function check($path = null, $module = null)
  408. {
  409. if (!$this->_logined) {
  410. return false;
  411. }
  412. $ruleList = $this->getRuleList();
  413. $rules = [];
  414. foreach ($ruleList as $k => $v) {
  415. $rules[] = $v['name'];
  416. }
  417. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  418. $url = strtolower(str_replace('.', '/', $url));
  419. return in_array($url, $rules) ? true : false;
  420. }
  421. /**
  422. * 判断是否登录
  423. * @return boolean
  424. */
  425. public function isLogin()
  426. {
  427. if ($this->_logined) {
  428. return true;
  429. }
  430. return false;
  431. }
  432. /**
  433. * 获取当前Token
  434. * @return string
  435. */
  436. public function getToken()
  437. {
  438. return $this->_token;
  439. }
  440. /**
  441. * 获取会员基本信息
  442. */
  443. public function getUserinfo()
  444. {
  445. $data = $this->_user->toArray();
  446. $allowFields = $this->getAllowFields();
  447. $userinfo = array_intersect_key($data, array_flip($allowFields));
  448. $userinfo = array_merge($userinfo, Token::get($this->_token));
  449. //用户钱包
  450. $userwallet = Db::name('user_wallet')->where('user_id',$this->_user->id)->find();
  451. $userinfo['wallet'] = $userwallet;
  452. //关注数量
  453. $userinfo['follow_num'] = Db::name('user_follow')->where('uid',$this->id)->count('id');
  454. //粉丝数量
  455. $userinfo['fans_num'] = Db::name('user_follow')->where('follow_uid',$this->id)->count('id');
  456. //装扮
  457. $usercar = "";
  458. $userheader = "";
  459. // 获取用户头像框信息
  460. $map = [
  461. 'a.user_id' => $this->id,
  462. 'a.is_using' => 1,
  463. 'a.end_time' => ['gt',time()],
  464. ];
  465. $backResult = Db::name('user_decorate')->alias('a')
  466. ->field('a.id,a.decorate_type,b.base_image,b.play_image')
  467. ->join('decorate b', 'a.decorate_id = b.id')
  468. ->where($map)->order('a.id desc')->select();
  469. $backResult = list_domain_image($backResult,['base_image','play_image']);
  470. if ($backResult) {
  471. foreach ($backResult as $k => $v) {
  472. $v['decorate_type'] == 1 && $usercar = $v['play_image'];
  473. $v['decorate_type'] == 2 && $userheader = $v['play_image'];
  474. }
  475. }
  476. //装扮
  477. $userinfo["usercar"] = $usercar;
  478. $userinfo["userheader"] = $userheader;
  479. //
  480. $userField = 'id,pay_password,openid,is_cool,is_manager,is_stealth,nickname,avatar,age_id,constellation_id,province_id,city_id,desc';
  481. $user = model('User')->field($userField)->where(["id" => $this->_user->id])->with(['useralipay','userbank','userauth'])->find();
  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['own_guild_id'] = 0;
  525. $own_guild_id = Db::name('guild')->where('user_id',$this->_user->id)->where('status',1)->value('id');
  526. if($own_guild_id){
  527. $userinfo['own_guild_id'] = $own_guild_id;
  528. }
  529. if ($this->power->private_messages == 1 ||$this->power->speak == 1) {
  530. $time = time();
  531. $updateArr = [];
  532. if ($this->power->private_messages_time < $time) {
  533. $updateArr['private_messages'] = 0;
  534. $this->power->private_messages = 0;
  535. }
  536. if ($this->power->speak_time < $time) {
  537. $updateArr['speak_time'] = 0;
  538. $this->power->speak = 0;
  539. }
  540. if (!empty($updateArr)) {
  541. UserPower::where(['user_id'=>$this->_user->id])->update($updateArr);
  542. }
  543. }
  544. if (!isset($this->power)) {
  545. $userPowerWhere['user_id'] = $this->_user->id;
  546. $userPower = model('UserPower')->where($userPowerWhere)->find();
  547. } else {
  548. $userPower = $this->power;
  549. }
  550. $userinfo['user_power'] = $userPower;
  551. //魅力等级
  552. $charm_info = Db::name('user_config_charm')->where('level',$this->charm_level)->find();
  553. $userinfo['charm_image'] = localpath_to_netpath($charm_info['image']);
  554. $userinfo['charm_color'] = $charm_info['color'];
  555. //财富等级
  556. $wealth_info = Db::name('user_config_wealth')->where('level',$this->wealth_level)->find();
  557. $userinfo['wealth_image'] = localpath_to_netpath($wealth_info['image']);
  558. $userinfo['wealth_color'] = $wealth_info['color'];
  559. //
  560. return $userinfo;
  561. }
  562. /**
  563. * 获取会员组别规则列表
  564. * @return array
  565. */
  566. public function getRuleList()
  567. {
  568. if ($this->rules) {
  569. return $this->rules;
  570. }
  571. $group = $this->_user->group;
  572. if (!$group) {
  573. return [];
  574. }
  575. $rules = explode(',', $group->rules);
  576. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  577. return $this->rules;
  578. }
  579. /**
  580. * 获取当前请求的URI
  581. * @return string
  582. */
  583. public function getRequestUri()
  584. {
  585. return $this->requestUri;
  586. }
  587. /**
  588. * 设置当前请求的URI
  589. * @param string $uri
  590. */
  591. public function setRequestUri($uri)
  592. {
  593. $this->requestUri = $uri;
  594. }
  595. /**
  596. * 获取允许输出的字段
  597. * @return array
  598. */
  599. public function getAllowFields()
  600. {
  601. return $this->allowFields;
  602. }
  603. /**
  604. * 设置允许输出的字段
  605. * @param array $fields
  606. */
  607. public function setAllowFields($fields)
  608. {
  609. $this->allowFields = $fields;
  610. }
  611. /**
  612. * 删除一个指定会员
  613. * @param int $user_id 会员ID
  614. * @return boolean
  615. */
  616. public function delete($user_id)
  617. {
  618. $user = User::get($user_id);
  619. if (!$user) {
  620. return false;
  621. }
  622. Db::startTrans();
  623. try {
  624. // 删除会员
  625. User::destroy($user_id);
  626. // 删除会员指定的所有Token
  627. Token::clear($user_id);
  628. Hook::listen("user_delete_successed", $user);
  629. Db::commit();
  630. } catch (Exception $e) {
  631. Db::rollback();
  632. $this->setError($e->getMessage());
  633. return false;
  634. }
  635. return true;
  636. }
  637. /**
  638. * 获取密码加密后的字符串
  639. * @param string $password 密码
  640. * @param string $salt 密码盐
  641. * @return string
  642. */
  643. public function getEncryptPassword($password, $salt = '')
  644. {
  645. return md5(md5($password) . $salt);
  646. }
  647. /**
  648. * 检测当前控制器和方法是否匹配传递的数组
  649. *
  650. * @param array $arr 需要验证权限的数组
  651. * @return boolean
  652. */
  653. public function match($arr = [])
  654. {
  655. $request = Request::instance();
  656. $arr = is_array($arr) ? $arr : explode(',', $arr);
  657. if (!$arr) {
  658. return false;
  659. }
  660. $arr = array_map('strtolower', $arr);
  661. // 是否存在
  662. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  663. return true;
  664. }
  665. // 没找到匹配
  666. return false;
  667. }
  668. /**
  669. * 设置会话有效时间
  670. * @param int $keeptime 默认为永久
  671. */
  672. public function keeptime($keeptime = 0)
  673. {
  674. $this->keeptime = $keeptime;
  675. }
  676. /**
  677. * 渲染用户数据
  678. * @param array $datalist 二维数组
  679. * @param mixed $fields 加载的字段列表
  680. * @param string $fieldkey 渲染的字段
  681. * @param string $renderkey 结果字段
  682. * @return array
  683. */
  684. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  685. {
  686. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  687. $ids = [];
  688. foreach ($datalist as $k => $v) {
  689. if (!isset($v[$fieldkey])) {
  690. continue;
  691. }
  692. $ids[] = $v[$fieldkey];
  693. }
  694. $list = [];
  695. if ($ids) {
  696. if (!in_array('id', $fields)) {
  697. $fields[] = 'id';
  698. }
  699. $ids = array_unique($ids);
  700. $selectlist = User::where('id', 'in', $ids)->column($fields);
  701. foreach ($selectlist as $k => $v) {
  702. $list[$v['id']] = $v;
  703. }
  704. }
  705. foreach ($datalist as $k => &$v) {
  706. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  707. }
  708. unset($v);
  709. return $datalist;
  710. }
  711. /**
  712. * 设置错误信息
  713. *
  714. * @param $error 错误信息
  715. * @return Auth
  716. */
  717. public function setError($error)
  718. {
  719. $this->_error = $error;
  720. return $this;
  721. }
  722. /**
  723. * 获取错误信息
  724. * @return string
  725. */
  726. public function getError()
  727. {
  728. return $this->_error ? __($this->_error) : '';
  729. }
  730. }