Authworker.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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::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. return $userinfo;
  364. }
  365. /**
  366. * 获取会员基本信息
  367. */
  368. public function getUserinfo()
  369. {
  370. $data = $this->_user->toArray();
  371. $allowFields = $this->getAllowFields();
  372. $userinfo = array_intersect_key($data, array_flip($allowFields));
  373. $userinfo = array_merge($userinfo, Tokenworker::get($this->_token));
  374. //追加
  375. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  376. $userinfo['idcard_z_image'] = one_domain_image($userinfo['idcard_z_image']);
  377. $userinfo['idcard_f_image'] = one_domain_image($userinfo['idcard_f_image']);
  378. $userinfo['jineng_image'] = one_domain_image($userinfo['jineng_image']);
  379. return $userinfo;
  380. }
  381. /**
  382. * 获取当前请求的URI
  383. * @return string
  384. */
  385. public function getRequestUri()
  386. {
  387. return $this->requestUri;
  388. }
  389. /**
  390. * 设置当前请求的URI
  391. * @param string $uri
  392. */
  393. public function setRequestUri($uri)
  394. {
  395. $this->requestUri = $uri;
  396. }
  397. /**
  398. * 获取允许输出的字段
  399. * @return array
  400. */
  401. public function getAllowFields()
  402. {
  403. return $this->allowFields;
  404. }
  405. /**
  406. * 设置允许输出的字段
  407. * @param array $fields
  408. */
  409. public function setAllowFields($fields)
  410. {
  411. $this->allowFields = $fields;
  412. }
  413. /**
  414. * 获取密码加密后的字符串
  415. * @param string $password 密码
  416. * @param string $salt 密码盐
  417. * @return string
  418. */
  419. public function getEncryptPassword($password)
  420. {
  421. return $password;
  422. // return md5(md5($password) . $salt);
  423. }
  424. /**
  425. * 检测当前控制器和方法是否匹配传递的数组
  426. *
  427. * @param array $arr 需要验证权限的数组
  428. * @return boolean
  429. */
  430. public function match($arr = [])
  431. {
  432. $request = Request::instance();
  433. $arr = is_array($arr) ? $arr : explode(',', $arr);
  434. if (!$arr) {
  435. return false;
  436. }
  437. $arr = array_map('strtolower', $arr);
  438. // 是否存在
  439. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  440. return true;
  441. }
  442. // 没找到匹配
  443. return false;
  444. }
  445. /**
  446. * 设置会话有效时间
  447. * @param int $keeptime 默认为永久
  448. */
  449. public function keeptime($keeptime = 0)
  450. {
  451. $this->keeptime = $keeptime;
  452. }
  453. /**
  454. * 渲染用户数据
  455. * @param array $datalist 二维数组
  456. * @param mixed $fields 加载的字段列表
  457. * @param string $fieldkey 渲染的字段
  458. * @param string $renderkey 结果字段
  459. * @return array
  460. */
  461. /*public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  462. {
  463. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  464. $ids = [];
  465. foreach ($datalist as $k => $v) {
  466. if (!isset($v[$fieldkey])) {
  467. continue;
  468. }
  469. $ids[] = $v[$fieldkey];
  470. }
  471. $list = [];
  472. if ($ids) {
  473. if (!in_array('id', $fields)) {
  474. $fields[] = 'id';
  475. }
  476. $ids = array_unique($ids);
  477. $selectlist = User::where('id', 'in', $ids)->column($fields);
  478. foreach ($selectlist as $k => $v) {
  479. $list[$v['id']] = $v;
  480. }
  481. }
  482. foreach ($datalist as $k => &$v) {
  483. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  484. }
  485. unset($v);
  486. return $datalist;
  487. }*/
  488. /**
  489. * 设置错误信息
  490. *
  491. * @param string $error 错误信息
  492. * @return Auth
  493. */
  494. public function setError($error)
  495. {
  496. $this->_error = $error;
  497. return $this;
  498. }
  499. /**
  500. * 获取错误信息
  501. * @return string
  502. */
  503. public function getError()
  504. {
  505. return $this->_error ? __($this->_error) : '';
  506. }
  507. }