Authdoctor.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. <?php
  2. namespace app\common\library;
  3. use app\common\model\Doctor;
  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 Authdoctor
  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', 'ruletype', 'nickname', 'avatar', 'gender','mobile',
  27. 'realname',
  28. 'idcard',
  29. 'idcard_z_image',
  30. 'idcard_f_image',
  31. 'idcard_status',
  32. 'doctor_image',
  33. 'doctor_status',
  34. 'english_status',
  35. 'keshi_id',
  36. 'hospital',
  37. 'goodat',
  38. 'level_id',
  39. 'info',
  40. ];
  41. public function __construct($options = [])
  42. {
  43. if ($config = Config::get('doctor')) {
  44. $this->config = array_merge($this->config, $config);
  45. }
  46. $this->options = array_merge($this->config, $options);
  47. }
  48. /**
  49. *
  50. * @param array $options 参数
  51. * @return Auth
  52. */
  53. public static function instance($options = [])
  54. {
  55. if (is_null(self::$instance)) {
  56. self::$instance = new static($options);
  57. }
  58. return self::$instance;
  59. }
  60. /**
  61. * 生成不重复的随机数字字母组合
  62. */
  63. function getUinqueNo($length = 8, $nos = [])
  64. {
  65. $newid = Random::build("alnum", $length);
  66. if (in_array($newid, $nos)) {
  67. $newid = $this->getUinqueNo($length, $nos);
  68. }
  69. return $newid;
  70. }
  71. /**
  72. * 获取User模型
  73. * @return User
  74. */
  75. public function getUser()
  76. {
  77. return $this->_user;
  78. }
  79. /**
  80. * 兼容调用user模型的属性
  81. *
  82. * @param string $name
  83. * @return mixed
  84. */
  85. public function __get($name)
  86. {
  87. return $this->_user ? $this->_user->$name : null;
  88. }
  89. /**
  90. * 兼容调用user模型的属性
  91. */
  92. public function __isset($name)
  93. {
  94. return isset($this->_user) ? isset($this->_user->$name) : false;
  95. }
  96. /**
  97. * 根据Token初始化
  98. *
  99. * @param string $token Token
  100. * @return boolean
  101. */
  102. public function init($token)
  103. {
  104. if ($this->_logined) {
  105. return true;
  106. }
  107. if ($this->_error) {
  108. return false;
  109. }
  110. $data = Tokendoctor::get($token);
  111. if (!$data) {
  112. return false;
  113. }
  114. $user_id = intval($data['user_id']);
  115. if ($user_id > 0) {
  116. $user = Doctor::get($user_id);
  117. if (!$user) {
  118. $this->setError('Account not exist');
  119. return false;
  120. }
  121. if ($user->status != 1) {
  122. $this->setError('Account is locked');
  123. return false;
  124. }
  125. $this->_user = $user;
  126. $this->_logined = true;
  127. $this->_token = $token;
  128. //初始化成功的事件
  129. // Hook::listen("company_init_successed", $this->_user);
  130. return true;
  131. } else {
  132. $this->setError('You are not logged in');
  133. return false;
  134. }
  135. }
  136. /**
  137. * 注册用户
  138. *
  139. * @param string $username 用户名
  140. * @param string $password 密码
  141. * @param string $email 邮箱
  142. * @param string $mobile 手机号
  143. * @param array $extend 扩展参数
  144. * @return boolean
  145. */
  146. public function register($username, $password, $email = '', $mobile = '', $extend = [])
  147. {
  148. // 检测用户名、昵称、邮箱、手机号是否存在
  149. /*if (User::getByUsername($username)) {
  150. $this->setError('Username already exist');
  151. return false;
  152. }
  153. if (User::getByNickname($username)) {
  154. $this->setError('Nickname already exist');
  155. return false;
  156. }
  157. if ($email && User::getByEmail($email)) {
  158. $this->setError('Email already exist');
  159. return false;
  160. }*/
  161. if(empty($mobile)){
  162. $this->setError('手机号必填');
  163. return false;
  164. }
  165. if ($mobile && Doctor::getByMobile($mobile)) {
  166. $this->setError('Mobile already exist');
  167. return false;
  168. }
  169. $ip = request()->ip();
  170. $time = time();
  171. $data = [
  172. // 'username' => $username,
  173. // 'password' => $password,
  174. // 'email' => $email,
  175. 'mobile' => $mobile,
  176. // 'level' => 1,
  177. // 'score' => 0,
  178. 'avatar' => '',
  179. ];
  180. $params = array_merge($data, [
  181. // 'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
  182. 'nickname' => get_rand_nick_name(),
  183. // 'salt' => Random::alnum(),
  184. // 'jointime' => $time,
  185. // 'joinip' => $ip,
  186. // 'logintime' => $time,
  187. // 'loginip' => $ip,
  188. // 'prevtime' => $time,
  189. 'status' => 1
  190. ]);
  191. // $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  192. $params = array_merge($params, $extend);
  193. //账号注册时需要开启事务,避免出现垃圾数据
  194. Db::startTrans();
  195. try {
  196. $user = Doctor::create($params, true);
  197. $this->_user = Doctor::get($user->id);
  198. /*$this->_user->username = 'd' . (10000 + $user->id);
  199. $this->_user->save();*/
  200. //设置Token
  201. $this->_token = Random::uuid();
  202. Tokendoctor::set($this->_token, $user->id, $this->keeptime);
  203. //设置登录状态
  204. $this->_logined = true;
  205. //注册钱包
  206. $wallet_id = Db::name('doctor_wallet')->insertGetId(['doctor_id'=>$user->id]);
  207. if(!$wallet_id){
  208. $this->setError('注册用户失败');
  209. Db::rollback();
  210. return false;
  211. }
  212. //注册info
  213. $info_id = Db::name('doctor_info')->insertGetId(['doctor_id'=>$user->id]);
  214. if(!$info_id){
  215. $this->setError('注册用户失败');
  216. Db::rollback();
  217. return false;
  218. }
  219. //[环信]注册用户。忽略失败
  220. /*$easemob = new Easemob();
  221. $rs = $easemob->user_create('doctor'.$user->id);
  222. if($rs === false){
  223. $this->setError('注册用户失败');
  224. Db::rollback();
  225. return false;
  226. }*/
  227. //腾讯im注册用户
  228. $tenim = new Tenim();
  229. $rs = $tenim->register('doctor'.$user->id,$params['nickname'],'');
  230. if($rs !== true){
  231. $this->setError($rs);
  232. Db::rollback();
  233. return false;
  234. }
  235. //注册成功的事件
  236. Db::commit();
  237. } catch (Exception $e) {
  238. $this->setError($e->getMessage());
  239. Db::rollback();
  240. return false;
  241. }
  242. return true;
  243. }
  244. /**
  245. * 用户登录
  246. *
  247. * @param string $account 账号,用户名、邮箱、手机号
  248. * @param string $password 密码
  249. * @return boolean
  250. */
  251. /*public function login($account, $password)
  252. {
  253. $field = 'mobile';
  254. $user = Doctor::get([$field => $account]);
  255. if (!$user) {
  256. $this->setError('Account is incorrect');
  257. return false;
  258. }
  259. if ($user->status != 1) {
  260. $this->setError('Account is locked');
  261. return false;
  262. }
  263. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  264. $this->setError('Password is incorrect');
  265. return false;
  266. }
  267. //直接登录员工
  268. return $this->direct($user->id);
  269. }*/
  270. /**
  271. * 退出
  272. *
  273. * @return boolean
  274. */
  275. public function logout()
  276. {
  277. if (!$this->_logined) {
  278. $this->setError('You are not logged in');
  279. return false;
  280. }
  281. //设置登录标识
  282. $this->_logined = false;
  283. //删除Token
  284. Tokendoctor::delete($this->_token);
  285. //退出成功的事件
  286. Hook::listen("user_logout_successed", $this->_user);
  287. return true;
  288. }
  289. /**
  290. * 修改密码
  291. * @param string $newpassword 新密码
  292. * @param string $oldpassword 旧密码
  293. * @param bool $ignoreoldpassword 忽略旧密码
  294. * @return boolean
  295. */
  296. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  297. {
  298. if (!$this->_logined) {
  299. $this->setError('You are not logged in');
  300. return false;
  301. }
  302. //判断旧密码是否正确
  303. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  304. Db::startTrans();
  305. try {
  306. $salt = Random::alnum();
  307. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  308. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  309. Token::delete($this->_token);
  310. //修改密码成功的事件
  311. Hook::listen("user_changepwd_successed", $this->_user);
  312. Db::commit();
  313. } catch (Exception $e) {
  314. Db::rollback();
  315. $this->setError($e->getMessage());
  316. return false;
  317. }
  318. return true;
  319. } else {
  320. $this->setError('Password is incorrect');
  321. return false;
  322. }
  323. }
  324. /**
  325. * 直接登录账号
  326. * @param int $user_id
  327. * @return boolean
  328. */
  329. public function direct($user_id)
  330. {
  331. $user = Doctor::get($user_id);
  332. if ($user) {
  333. Db::startTrans();
  334. try {
  335. $ip = request()->ip();
  336. $time = time();
  337. //判断连续登录和最大连续登录
  338. /*if ($user->logintime < \fast\Date::unixtime('day')) {
  339. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  340. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  341. }*/
  342. // $user->prevtime = $user->logintime;
  343. //记录本次登录的IP和时间
  344. // $user->loginip = $ip;
  345. // $user->logintime = $time;
  346. //重置登录失败次数
  347. // $user->loginfailure = 0;
  348. // $user->save();
  349. $this->_user = $user;
  350. $this->_token = Random::uuid();
  351. Tokendoctor::set($this->_token, $user->id, $this->keeptime);
  352. $this->_logined = true;
  353. //登录成功的事件
  354. Hook::listen("user_login_successed", $this->_user);
  355. Db::commit();
  356. } catch (Exception $e) {
  357. Db::rollback();
  358. $this->setError($e->getMessage());
  359. return false;
  360. }
  361. return true;
  362. } else {
  363. return false;
  364. }
  365. }
  366. /**
  367. * 判断是否登录
  368. * @return boolean
  369. */
  370. public function isLogin()
  371. {
  372. if ($this->_logined) {
  373. return true;
  374. }
  375. return false;
  376. }
  377. /**
  378. * 获取当前Token
  379. * @return string
  380. */
  381. public function getToken()
  382. {
  383. return $this->_token;
  384. }
  385. public function getUserinfo_simple(){
  386. $userinfo = Tokendoctor::get($this->_token);
  387. //是否完成用户资料
  388. $data = $this->_user->toArray();
  389. if(empty($data['idcard'])){
  390. $userinfo['finish_profile'] = 0;
  391. }else{
  392. $userinfo['finish_profile'] = 1;
  393. }
  394. return $userinfo;
  395. }
  396. /**
  397. * 获取会员基本信息
  398. */
  399. public function getUserinfo()
  400. {
  401. $data = $this->_user->toArray();
  402. $allowFields = $this->getAllowFields();
  403. $userinfo = array_intersect_key($data, array_flip($allowFields));
  404. $userinfo = array_merge($userinfo, Tokendoctor::get($this->_token));
  405. //追加
  406. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  407. $userinfo['keshi_name'] = Db::name('keshi')->where('id',$userinfo['keshi_id'])->value('name');
  408. $userinfo['level_name'] = Db::name('doctor_level')->where('id',$userinfo['level_id'])->value('name');
  409. //info
  410. $userinfo['doctor_info'] = Db::name('doctor_info')->where('doctor_id',$this->id)->find();
  411. $userinfo['wallet'] = Db::name('doctor_wallet')->where('doctor_id',$this->id)->find();
  412. //是否完成用户资料
  413. if(empty($data['idcard'])){
  414. $userinfo['finish_profile'] = 0;
  415. }else{
  416. $userinfo['finish_profile'] = 1;
  417. }
  418. return $userinfo;
  419. }
  420. /**
  421. * 获取当前请求的URI
  422. * @return string
  423. */
  424. public function getRequestUri()
  425. {
  426. return $this->requestUri;
  427. }
  428. /**
  429. * 设置当前请求的URI
  430. * @param string $uri
  431. */
  432. public function setRequestUri($uri)
  433. {
  434. $this->requestUri = $uri;
  435. }
  436. /**
  437. * 获取允许输出的字段
  438. * @return array
  439. */
  440. public function getAllowFields()
  441. {
  442. return $this->allowFields;
  443. }
  444. /**
  445. * 设置允许输出的字段
  446. * @param array $fields
  447. */
  448. public function setAllowFields($fields)
  449. {
  450. $this->allowFields = $fields;
  451. }
  452. /**
  453. * 获取密码加密后的字符串
  454. * @param string $password 密码
  455. * @param string $salt 密码盐
  456. * @return string
  457. */
  458. public function getEncryptPassword($password, $salt = '')
  459. {
  460. return md5(md5($password) . $salt);
  461. }
  462. /**
  463. * 检测当前控制器和方法是否匹配传递的数组
  464. *
  465. * @param array $arr 需要验证权限的数组
  466. * @return boolean
  467. */
  468. public function match($arr = [])
  469. {
  470. $request = Request::instance();
  471. $arr = is_array($arr) ? $arr : explode(',', $arr);
  472. if (!$arr) {
  473. return false;
  474. }
  475. $arr = array_map('strtolower', $arr);
  476. // 是否存在
  477. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  478. return true;
  479. }
  480. // 没找到匹配
  481. return false;
  482. }
  483. /**
  484. * 设置会话有效时间
  485. * @param int $keeptime 默认为永久
  486. */
  487. public function keeptime($keeptime = 0)
  488. {
  489. $this->keeptime = $keeptime;
  490. }
  491. /**
  492. * 渲染用户数据
  493. * @param array $datalist 二维数组
  494. * @param mixed $fields 加载的字段列表
  495. * @param string $fieldkey 渲染的字段
  496. * @param string $renderkey 结果字段
  497. * @return array
  498. */
  499. /*public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  500. {
  501. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  502. $ids = [];
  503. foreach ($datalist as $k => $v) {
  504. if (!isset($v[$fieldkey])) {
  505. continue;
  506. }
  507. $ids[] = $v[$fieldkey];
  508. }
  509. $list = [];
  510. if ($ids) {
  511. if (!in_array('id', $fields)) {
  512. $fields[] = 'id';
  513. }
  514. $ids = array_unique($ids);
  515. $selectlist = User::where('id', 'in', $ids)->column($fields);
  516. foreach ($selectlist as $k => $v) {
  517. $list[$v['id']] = $v;
  518. }
  519. }
  520. foreach ($datalist as $k => &$v) {
  521. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  522. }
  523. unset($v);
  524. return $datalist;
  525. }*/
  526. /**
  527. * 设置错误信息
  528. *
  529. * @param string $error 错误信息
  530. * @return Auth
  531. */
  532. public function setError($error)
  533. {
  534. $this->_error = $error;
  535. return $this;
  536. }
  537. /**
  538. * 获取错误信息
  539. * @return string
  540. */
  541. public function getError()
  542. {
  543. return $this->_error ? __($this->_error) : '';
  544. }
  545. }