Authdoctor.php 16 KB

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