Authworker.php 15 KB

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