Authworker.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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(['password' => $newpassword]);
  285. Tokenworker::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. $user->prevtime = $user->logintime;
  314. //记录本次登录的IP和时间
  315. $user->loginip = $ip;
  316. $user->logintime = $time;
  317. $user->save();
  318. $this->_user = $user;
  319. $this->_token = Random::uuid();
  320. Tokenworker::set($this->_token, $user->id, $this->keeptime);
  321. $this->_logined = true;
  322. //登录成功的事件
  323. Hook::listen("user_login_successed", $this->_user);
  324. Db::commit();
  325. } catch (Exception $e) {
  326. Db::rollback();
  327. $this->setError($e->getMessage());
  328. return false;
  329. }
  330. return true;
  331. } else {
  332. return false;
  333. }
  334. }
  335. /**
  336. * 判断是否登录
  337. * @return boolean
  338. */
  339. public function isLogin()
  340. {
  341. if ($this->_logined) {
  342. return true;
  343. }
  344. return false;
  345. }
  346. /**
  347. * 获取当前Token
  348. * @return string
  349. */
  350. public function getToken()
  351. {
  352. return $this->_token;
  353. }
  354. public function getUserinfo_simple(){
  355. $userinfo = Tokenworker::get($this->_token);
  356. //是否完成用户资料
  357. $data = $this->_user->toArray();
  358. return $userinfo;
  359. }
  360. /**
  361. * 获取会员基本信息
  362. */
  363. public function getUserinfo()
  364. {
  365. $data = $this->_user->toArray();
  366. $allowFields = $this->getAllowFields();
  367. $userinfo = array_intersect_key($data, array_flip($allowFields));
  368. $userinfo = array_merge($userinfo, Tokenworker::get($this->_token));
  369. //追加
  370. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  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, $salt = '')
  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. }