Authworker.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. <?php
  2. namespace app\common\library;
  3. use app\common\model\Worker;
  4. use fast\Random;
  5. use think\Config;
  6. use think\Db;
  7. use think\Exception;
  8. use think\Hook;
  9. use think\Request;
  10. use think\Validate;
  11. class Authworker
  12. {
  13. protected static $instance = null;
  14. protected $_error = '';
  15. protected $_logined = false;
  16. protected $_user = null;
  17. protected $_token = '';
  18. //Token默认有效时长
  19. protected $keeptime = 2592000;
  20. protected $requestUri = '';
  21. protected $rules = [];
  22. //默认配置
  23. protected $config = [];
  24. protected $options = [];
  25. protected $allowFields = [
  26. 'id', 'truename', 'avatar', 'gonghao','mobile',
  27. ];
  28. public function __construct($options = [])
  29. {
  30. if ($config = Config::get('worker')) {
  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. * 兼容调用user模型的属性
  67. */
  68. public function __isset($name)
  69. {
  70. return isset($this->_user) ? isset($this->_user->$name) : false;
  71. }
  72. /**
  73. * 根据Token初始化
  74. *
  75. * @param string $token Token
  76. * @return boolean
  77. */
  78. public function init($token)
  79. {
  80. if ($this->_logined) {
  81. return true;
  82. }
  83. if ($this->_error) {
  84. return false;
  85. }
  86. $data = Tokenworker::get($token);
  87. if (!$data) {
  88. return false;
  89. }
  90. $user_id = intval($data['user_id']);
  91. if ($user_id > 0) {
  92. $user = Worker::get($user_id);
  93. if (!$user) {
  94. $this->setError('Account not exist');
  95. return false;
  96. }
  97. if ($user->status != 1) {
  98. $this->setError('Account is locked');
  99. return false;
  100. }
  101. $this->_user = $user;
  102. $this->_logined = true;
  103. $this->_token = $token;
  104. //初始化成功的事件
  105. // Hook::listen("company_init_successed", $this->_user);
  106. return true;
  107. } else {
  108. $this->setError('You are not logged in');
  109. return false;
  110. }
  111. }
  112. /**
  113. * 注册用户
  114. *
  115. * @param string $username 用户名
  116. * @param string $password 密码
  117. * @param string $email 邮箱
  118. * @param string $mobile 手机号
  119. * @param array $extend 扩展参数
  120. * @return boolean
  121. */
  122. public function register($username, $password, $email = '', $mobile = '', $extend = [])
  123. {
  124. // 检测用户名、昵称、邮箱、手机号是否存在
  125. /*if (User::getByUsername($username)) {
  126. $this->setError('Username already exist');
  127. return false;
  128. }
  129. if (User::getByNickname($username)) {
  130. $this->setError('Nickname already exist');
  131. return false;
  132. }
  133. if ($email && User::getByEmail($email)) {
  134. $this->setError('Email already exist');
  135. return false;
  136. }*/
  137. if(empty($mobile)){
  138. $this->setError('手机号必填');
  139. return false;
  140. }
  141. if ($mobile && Worker::getByMobile($mobile)) {
  142. $this->setError('Mobile already exist');
  143. return false;
  144. }
  145. $ip = request()->ip();
  146. $time = time();
  147. $data = [
  148. // 'username' => $username,
  149. // 'password' => $password,
  150. // 'email' => $email,
  151. 'mobile' => $mobile,
  152. // 'level' => 1,
  153. // 'score' => 0,
  154. 'avatar' => config('site.worker_default_avatar'),
  155. ];
  156. $params = array_merge($data, [
  157. // 'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
  158. 'nickname' => get_rand_nick_name(),
  159. // 'salt' => Random::alnum(),
  160. // 'jointime' => $time,
  161. // 'joinip' => $ip,
  162. // 'logintime' => $time,
  163. // 'loginip' => $ip,
  164. // 'prevtime' => $time,
  165. 'status' => 1
  166. ]);
  167. // $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  168. $params = array_merge($params, $extend);
  169. //账号注册时需要开启事务,避免出现垃圾数据
  170. Db::startTrans();
  171. try {
  172. $user = Worker::create($params, true);
  173. $this->_user = Worker::get($user->id);
  174. /*$this->_user->username = 'd' . (10000 + $user->id);
  175. $this->_user->save();*/
  176. //设置Token
  177. $this->_token = Random::uuid();
  178. Tokenworker::set($this->_token, $user->id, $this->keeptime);
  179. //设置登录状态
  180. $this->_logined = true;
  181. //注册钱包
  182. $wallet_id = Db::name('worker_wallet')->insertGetId(['worker_id'=>$user->id]);
  183. if(!$wallet_id){
  184. $this->setError('注册用户失败');
  185. Db::rollback();
  186. return false;
  187. }
  188. //注册info
  189. $info_id = Db::name('worker_info')->insertGetId(['worker_id'=>$user->id]);
  190. if(!$info_id){
  191. $this->setError('注册用户失败');
  192. Db::rollback();
  193. return false;
  194. }
  195. //[环信]注册用户。忽略失败
  196. /*$easemob = new Easemob();
  197. $rs = $easemob->user_create('worker'.$user->id);
  198. if($rs === false){
  199. $this->setError('注册用户失败');
  200. Db::rollback();
  201. return false;
  202. }*/
  203. //腾讯im注册用户
  204. $tenim = new Tenim();
  205. $rs = $tenim->register('worker'.$user->id,$params['nickname'],'');
  206. if($rs !== true){
  207. $this->setError($rs);
  208. Db::rollback();
  209. return false;
  210. }
  211. //注册成功的事件
  212. Db::commit();
  213. } catch (Exception $e) {
  214. $this->setError($e->getMessage());
  215. Db::rollback();
  216. return false;
  217. }
  218. return true;
  219. }
  220. /**
  221. * 用户登录
  222. *
  223. * @param string $account 账号,用户名、邮箱、手机号
  224. * @param string $password 密码
  225. * @return boolean
  226. */
  227. /*public function login($account, $password)
  228. {
  229. $field = 'mobile';
  230. $user = Worker::get([$field => $account]);
  231. if (!$user) {
  232. $this->setError('Account is incorrect');
  233. return false;
  234. }
  235. if ($user->status != 1) {
  236. $this->setError('Account is locked');
  237. return false;
  238. }
  239. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  240. $this->setError('Password is incorrect');
  241. return false;
  242. }
  243. //直接登录员工
  244. return $this->direct($user->id);
  245. }*/
  246. /**
  247. * 退出
  248. *
  249. * @return boolean
  250. */
  251. public function logout()
  252. {
  253. if (!$this->_logined) {
  254. $this->setError('You are not logged in');
  255. return false;
  256. }
  257. //设置登录标识
  258. $this->_logined = false;
  259. //删除Token
  260. Tokenworker::delete($this->_token);
  261. //退出成功的事件
  262. Hook::listen("user_logout_successed", $this->_user);
  263. return true;
  264. }
  265. /**
  266. * 修改密码
  267. * @param string $newpassword 新密码
  268. * @param string $oldpassword 旧密码
  269. * @param bool $ignoreoldpassword 忽略旧密码
  270. * @return boolean
  271. */
  272. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  273. {
  274. if (!$this->_logined) {
  275. $this->setError('You are not logged in');
  276. return false;
  277. }
  278. //判断旧密码是否正确
  279. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  280. Db::startTrans();
  281. try {
  282. $salt = Random::alnum();
  283. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  284. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  285. Token::delete($this->_token);
  286. //修改密码成功的事件
  287. Hook::listen("user_changepwd_successed", $this->_user);
  288. Db::commit();
  289. } catch (Exception $e) {
  290. Db::rollback();
  291. $this->setError($e->getMessage());
  292. return false;
  293. }
  294. return true;
  295. } else {
  296. $this->setError('Password is incorrect');
  297. return false;
  298. }
  299. }
  300. /**
  301. * 直接登录账号
  302. * @param int $user_id
  303. * @return boolean
  304. */
  305. public function direct($user_id)
  306. {
  307. $user = Worker::get($user_id);
  308. if ($user) {
  309. Db::startTrans();
  310. try {
  311. $ip = request()->ip();
  312. $time = time();
  313. //判断连续登录和最大连续登录
  314. /*if ($user->logintime < \fast\Date::unixtime('day')) {
  315. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  316. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  317. }*/
  318. // $user->prevtime = $user->logintime;
  319. //记录本次登录的IP和时间
  320. // $user->loginip = $ip;
  321. // $user->logintime = $time;
  322. //重置登录失败次数
  323. // $user->loginfailure = 0;
  324. // $user->save();
  325. $this->_user = $user;
  326. $this->_token = Random::uuid();
  327. Tokenworker::set($this->_token, $user->id, $this->keeptime);
  328. $this->_logined = true;
  329. //登录成功的事件
  330. Hook::listen("user_login_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. return false;
  340. }
  341. }
  342. /**
  343. * 判断是否登录
  344. * @return boolean
  345. */
  346. public function isLogin()
  347. {
  348. if ($this->_logined) {
  349. return true;
  350. }
  351. return false;
  352. }
  353. /**
  354. * 获取当前Token
  355. * @return string
  356. */
  357. public function getToken()
  358. {
  359. return $this->_token;
  360. }
  361. public function getUserinfo_simple(){
  362. $userinfo = Tokenworker::get($this->_token);
  363. //是否完成用户资料
  364. $data = $this->_user->toArray();
  365. if(empty($data['idcard'])){
  366. $userinfo['finish_profile'] = 0;
  367. }else{
  368. $userinfo['finish_profile'] = 1;
  369. }
  370. return $userinfo;
  371. }
  372. /**
  373. * 获取会员基本信息
  374. */
  375. public function getUserinfo()
  376. {
  377. $data = $this->_user->toArray();
  378. $allowFields = $this->getAllowFields();
  379. $userinfo = array_intersect_key($data, array_flip($allowFields));
  380. $userinfo = array_merge($userinfo, Tokenworker::get($this->_token));
  381. //追加
  382. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  383. $userinfo['keshi_name'] = Db::name('keshi')->where('id',$userinfo['keshi_id'])->value('name');
  384. $userinfo['level_name'] = Db::name('worker_level')->where('id',$userinfo['level_id'])->value('name');
  385. //info
  386. $userinfo['worker_info'] = Db::name('worker_info')->where('worker_id',$this->id)->find();
  387. $userinfo['wallet'] = Db::name('worker_wallet')->where('worker_id',$this->id)->find();
  388. //是否完成用户资料
  389. if(empty($data['idcard'])){
  390. $userinfo['finish_profile'] = 0;
  391. }else{
  392. $userinfo['finish_profile'] = 1;
  393. }
  394. //待接图文订单
  395. $where = [
  396. 'worker_id'=>$this->id,
  397. 'ordertype'=>1,
  398. 'status'=>10,
  399. ];
  400. $userinfo['wenzhen_text_noaccept_num'] = Db::name('wenzhen_order')->where($where)->count();
  401. //待接视频订单
  402. $where = [
  403. 'worker_id'=>$this->id,
  404. 'ordertype'=>2,
  405. 'status'=>10,
  406. ];
  407. $userinfo['wenzhen_video_noaccept_num'] = Db::name('wenzhen_order')->where($where)->count();
  408. //待接订单
  409. $userinfo['wenzhen_noaccept_num'] = $userinfo['wenzhen_text_noaccept_num'] + $userinfo['wenzhen_video_noaccept_num'];
  410. return $userinfo;
  411. }
  412. /**
  413. * 获取当前请求的URI
  414. * @return string
  415. */
  416. public function getRequestUri()
  417. {
  418. return $this->requestUri;
  419. }
  420. /**
  421. * 设置当前请求的URI
  422. * @param string $uri
  423. */
  424. public function setRequestUri($uri)
  425. {
  426. $this->requestUri = $uri;
  427. }
  428. /**
  429. * 获取允许输出的字段
  430. * @return array
  431. */
  432. public function getAllowFields()
  433. {
  434. return $this->allowFields;
  435. }
  436. /**
  437. * 设置允许输出的字段
  438. * @param array $fields
  439. */
  440. public function setAllowFields($fields)
  441. {
  442. $this->allowFields = $fields;
  443. }
  444. /**
  445. * 获取密码加密后的字符串
  446. * @param string $password 密码
  447. * @param string $salt 密码盐
  448. * @return string
  449. */
  450. public function getEncryptPassword($password, $salt = '')
  451. {
  452. return md5(md5($password) . $salt);
  453. }
  454. /**
  455. * 检测当前控制器和方法是否匹配传递的数组
  456. *
  457. * @param array $arr 需要验证权限的数组
  458. * @return boolean
  459. */
  460. public function match($arr = [])
  461. {
  462. $request = Request::instance();
  463. $arr = is_array($arr) ? $arr : explode(',', $arr);
  464. if (!$arr) {
  465. return false;
  466. }
  467. $arr = array_map('strtolower', $arr);
  468. // 是否存在
  469. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  470. return true;
  471. }
  472. // 没找到匹配
  473. return false;
  474. }
  475. /**
  476. * 设置会话有效时间
  477. * @param int $keeptime 默认为永久
  478. */
  479. public function keeptime($keeptime = 0)
  480. {
  481. $this->keeptime = $keeptime;
  482. }
  483. /**
  484. * 渲染用户数据
  485. * @param array $datalist 二维数组
  486. * @param mixed $fields 加载的字段列表
  487. * @param string $fieldkey 渲染的字段
  488. * @param string $renderkey 结果字段
  489. * @return array
  490. */
  491. /*public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  492. {
  493. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  494. $ids = [];
  495. foreach ($datalist as $k => $v) {
  496. if (!isset($v[$fieldkey])) {
  497. continue;
  498. }
  499. $ids[] = $v[$fieldkey];
  500. }
  501. $list = [];
  502. if ($ids) {
  503. if (!in_array('id', $fields)) {
  504. $fields[] = 'id';
  505. }
  506. $ids = array_unique($ids);
  507. $selectlist = User::where('id', 'in', $ids)->column($fields);
  508. foreach ($selectlist as $k => $v) {
  509. $list[$v['id']] = $v;
  510. }
  511. }
  512. foreach ($datalist as $k => &$v) {
  513. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  514. }
  515. unset($v);
  516. return $datalist;
  517. }*/
  518. /**
  519. * 设置错误信息
  520. *
  521. * @param string $error 错误信息
  522. * @return Auth
  523. */
  524. public function setError($error)
  525. {
  526. $this->_error = $error;
  527. return $this;
  528. }
  529. /**
  530. * 获取错误信息
  531. * @return string
  532. */
  533. public function getError()
  534. {
  535. return $this->_error ? __($this->_error) : '';
  536. }
  537. }