Authdoctor.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. //注册成功的事件
  227. Db::commit();
  228. } catch (Exception $e) {
  229. $this->setError($e->getMessage());
  230. Db::rollback();
  231. return false;
  232. }
  233. return true;
  234. }
  235. /**
  236. * 用户登录
  237. *
  238. * @param string $account 账号,用户名、邮箱、手机号
  239. * @param string $password 密码
  240. * @return boolean
  241. */
  242. /*public function login($account, $password)
  243. {
  244. $field = 'mobile';
  245. $user = Doctor::get([$field => $account]);
  246. if (!$user) {
  247. $this->setError('Account is incorrect');
  248. return false;
  249. }
  250. if ($user->status != 1) {
  251. $this->setError('Account is locked');
  252. return false;
  253. }
  254. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  255. $this->setError('Password is incorrect');
  256. return false;
  257. }
  258. //直接登录员工
  259. return $this->direct($user->id);
  260. }*/
  261. /**
  262. * 退出
  263. *
  264. * @return boolean
  265. */
  266. public function logout()
  267. {
  268. if (!$this->_logined) {
  269. $this->setError('You are not logged in');
  270. return false;
  271. }
  272. //设置登录标识
  273. $this->_logined = false;
  274. //删除Token
  275. Tokendoctor::delete($this->_token);
  276. //退出成功的事件
  277. Hook::listen("user_logout_successed", $this->_user);
  278. return true;
  279. }
  280. /**
  281. * 修改密码
  282. * @param string $newpassword 新密码
  283. * @param string $oldpassword 旧密码
  284. * @param bool $ignoreoldpassword 忽略旧密码
  285. * @return boolean
  286. */
  287. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  288. {
  289. if (!$this->_logined) {
  290. $this->setError('You are not logged in');
  291. return false;
  292. }
  293. //判断旧密码是否正确
  294. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  295. Db::startTrans();
  296. try {
  297. $salt = Random::alnum();
  298. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  299. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  300. Token::delete($this->_token);
  301. //修改密码成功的事件
  302. Hook::listen("user_changepwd_successed", $this->_user);
  303. Db::commit();
  304. } catch (Exception $e) {
  305. Db::rollback();
  306. $this->setError($e->getMessage());
  307. return false;
  308. }
  309. return true;
  310. } else {
  311. $this->setError('Password is incorrect');
  312. return false;
  313. }
  314. }
  315. /**
  316. * 直接登录账号
  317. * @param int $user_id
  318. * @return boolean
  319. */
  320. public function direct($user_id)
  321. {
  322. $user = Doctor::get($user_id);
  323. if ($user) {
  324. Db::startTrans();
  325. try {
  326. $ip = request()->ip();
  327. $time = time();
  328. //判断连续登录和最大连续登录
  329. /*if ($user->logintime < \fast\Date::unixtime('day')) {
  330. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  331. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  332. }*/
  333. // $user->prevtime = $user->logintime;
  334. //记录本次登录的IP和时间
  335. // $user->loginip = $ip;
  336. // $user->logintime = $time;
  337. //重置登录失败次数
  338. // $user->loginfailure = 0;
  339. // $user->save();
  340. $this->_user = $user;
  341. $this->_token = Random::uuid();
  342. Tokendoctor::set($this->_token, $user->id, $this->keeptime);
  343. $this->_logined = true;
  344. //登录成功的事件
  345. Hook::listen("user_login_successed", $this->_user);
  346. Db::commit();
  347. } catch (Exception $e) {
  348. Db::rollback();
  349. $this->setError($e->getMessage());
  350. return false;
  351. }
  352. return true;
  353. } else {
  354. return false;
  355. }
  356. }
  357. /**
  358. * 判断是否登录
  359. * @return boolean
  360. */
  361. public function isLogin()
  362. {
  363. if ($this->_logined) {
  364. return true;
  365. }
  366. return false;
  367. }
  368. /**
  369. * 获取当前Token
  370. * @return string
  371. */
  372. public function getToken()
  373. {
  374. return $this->_token;
  375. }
  376. public function getUserinfo_simple(){
  377. $userinfo = Tokendoctor::get($this->_token);
  378. return $userinfo;
  379. }
  380. /**
  381. * 获取会员基本信息
  382. */
  383. public function getUserinfo()
  384. {
  385. $data = $this->_user->toArray();
  386. $allowFields = $this->getAllowFields();
  387. $userinfo = array_intersect_key($data, array_flip($allowFields));
  388. $userinfo = array_merge($userinfo, Tokendoctor::get($this->_token));
  389. //追加
  390. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  391. $userinfo['level_name'] = Db::name('keshi')->where('id',$userinfo['keshi_id'])->value('name');
  392. $userinfo['keshi_name'] = Db::name('doctor_level')->where('id',$userinfo['level_id'])->value('name');
  393. //info
  394. $userinfo['doctor_info'] = Db::name('doctor_info')->where('doctor_id',$this->id)->find();
  395. $userinfo['wallet'] = Db::name('doctor_wallet')->where('doctor_id',$this->id)->find();
  396. return $userinfo;
  397. }
  398. /**
  399. * 获取当前请求的URI
  400. * @return string
  401. */
  402. public function getRequestUri()
  403. {
  404. return $this->requestUri;
  405. }
  406. /**
  407. * 设置当前请求的URI
  408. * @param string $uri
  409. */
  410. public function setRequestUri($uri)
  411. {
  412. $this->requestUri = $uri;
  413. }
  414. /**
  415. * 获取允许输出的字段
  416. * @return array
  417. */
  418. public function getAllowFields()
  419. {
  420. return $this->allowFields;
  421. }
  422. /**
  423. * 设置允许输出的字段
  424. * @param array $fields
  425. */
  426. public function setAllowFields($fields)
  427. {
  428. $this->allowFields = $fields;
  429. }
  430. /**
  431. * 获取密码加密后的字符串
  432. * @param string $password 密码
  433. * @param string $salt 密码盐
  434. * @return string
  435. */
  436. public function getEncryptPassword($password, $salt = '')
  437. {
  438. return md5(md5($password) . $salt);
  439. }
  440. /**
  441. * 检测当前控制器和方法是否匹配传递的数组
  442. *
  443. * @param array $arr 需要验证权限的数组
  444. * @return boolean
  445. */
  446. public function match($arr = [])
  447. {
  448. $request = Request::instance();
  449. $arr = is_array($arr) ? $arr : explode(',', $arr);
  450. if (!$arr) {
  451. return false;
  452. }
  453. $arr = array_map('strtolower', $arr);
  454. // 是否存在
  455. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  456. return true;
  457. }
  458. // 没找到匹配
  459. return false;
  460. }
  461. /**
  462. * 设置会话有效时间
  463. * @param int $keeptime 默认为永久
  464. */
  465. public function keeptime($keeptime = 0)
  466. {
  467. $this->keeptime = $keeptime;
  468. }
  469. /**
  470. * 渲染用户数据
  471. * @param array $datalist 二维数组
  472. * @param mixed $fields 加载的字段列表
  473. * @param string $fieldkey 渲染的字段
  474. * @param string $renderkey 结果字段
  475. * @return array
  476. */
  477. /*public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  478. {
  479. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  480. $ids = [];
  481. foreach ($datalist as $k => $v) {
  482. if (!isset($v[$fieldkey])) {
  483. continue;
  484. }
  485. $ids[] = $v[$fieldkey];
  486. }
  487. $list = [];
  488. if ($ids) {
  489. if (!in_array('id', $fields)) {
  490. $fields[] = 'id';
  491. }
  492. $ids = array_unique($ids);
  493. $selectlist = User::where('id', 'in', $ids)->column($fields);
  494. foreach ($selectlist as $k => $v) {
  495. $list[$v['id']] = $v;
  496. }
  497. }
  498. foreach ($datalist as $k => &$v) {
  499. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  500. }
  501. unset($v);
  502. return $datalist;
  503. }*/
  504. /**
  505. * 设置错误信息
  506. *
  507. * @param string $error 错误信息
  508. * @return Auth
  509. */
  510. public function setError($error)
  511. {
  512. $this->_error = $error;
  513. return $this;
  514. }
  515. /**
  516. * 获取错误信息
  517. * @return string
  518. */
  519. public function getError()
  520. {
  521. return $this->_error ? __($this->_error) : '';
  522. }
  523. }