Authworker.php 15 KB

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