Authworker.php 15 KB

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