Authcoach.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. <?php
  2. namespace app\common\library;
  3. use app\common\model\Coach;
  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 Authcoach
  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 = ['id', 'username','nickname', 'mobile', 'avatar'];
  26. public function __construct($options = [])
  27. {
  28. if ($config = Config::get('coach')) {
  29. $this->config = array_merge($this->config, $config);
  30. }
  31. $this->options = array_merge($this->config, $options);
  32. }
  33. /**
  34. *
  35. * @param array $options 参数
  36. * @return Auth
  37. */
  38. public static function instance($options = [])
  39. {
  40. if (is_null(self::$instance)) {
  41. self::$instance = new static($options);
  42. }
  43. return self::$instance;
  44. }
  45. /**
  46. * 生成不重复的随机数字字母组合
  47. */
  48. function getUinqueNo($length = 8, $nos = [])
  49. {
  50. $newid = Random::build("alnum", $length);
  51. if (in_array($newid, $nos)) {
  52. $newid = $this->getUinqueNo($length, $nos);
  53. }
  54. return $newid;
  55. }
  56. /**
  57. * 获取User模型
  58. * @return User
  59. */
  60. public function getUser()
  61. {
  62. return $this->_user;
  63. }
  64. /**
  65. * 兼容调用user模型的属性
  66. *
  67. * @param string $name
  68. * @return mixed
  69. */
  70. public function __get($name)
  71. {
  72. return $this->_user ? $this->_user->$name : null;
  73. }
  74. /**
  75. * 兼容调用user模型的属性
  76. */
  77. public function __isset($name)
  78. {
  79. return isset($this->_user) ? isset($this->_user->$name) : false;
  80. }
  81. /**
  82. * 根据Token初始化
  83. *
  84. * @param string $token Token
  85. * @return boolean
  86. */
  87. public function init($token)
  88. {
  89. if ($this->_logined) {
  90. return true;
  91. }
  92. if ($this->_error) {
  93. return false;
  94. }
  95. $data = Tokencoach::get($token);
  96. if (!$data) {
  97. return false;
  98. }
  99. $user_id = intval($data['user_id']);
  100. if ($user_id > 0) {
  101. $user = Coach::get($user_id);
  102. if (!$user) {
  103. $this->setError('Account not exist');
  104. return false;
  105. }
  106. if ($user->status != 1) {
  107. $this->setError('Account is locked');
  108. return false;
  109. }
  110. $this->_user = $user;
  111. $this->_logined = true;
  112. $this->_token = $token;
  113. //初始化成功的事件
  114. // Hook::listen("company_init_successed", $this->_user);
  115. return true;
  116. } else {
  117. $this->setError('You are not logged in');
  118. return false;
  119. }
  120. }
  121. /**
  122. * 用户登录
  123. *
  124. * @param string $account 账号,用户名、邮箱、手机号
  125. * @param string $password 密码
  126. * @return boolean
  127. */
  128. public function login($account, $password)
  129. {
  130. $field = 'mobile';
  131. $user = Coach::get([$field => $account]);
  132. if (!$user) {
  133. $this->setError('Account is incorrect');
  134. return false;
  135. }
  136. if ($user->status != 1) {
  137. $this->setError('Account is locked');
  138. return false;
  139. }
  140. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  141. $this->setError('Password is incorrect');
  142. return false;
  143. }
  144. //直接登录员工
  145. return $this->direct($user->id);
  146. }
  147. /**
  148. * 退出
  149. *
  150. * @return boolean
  151. */
  152. public function logout()
  153. {
  154. if (!$this->_logined) {
  155. $this->setError('You are not logged in');
  156. return false;
  157. }
  158. //设置登录标识
  159. $this->_logined = false;
  160. //删除Token
  161. Tokencoach::delete($this->_token);
  162. //退出成功的事件
  163. Hook::listen("user_logout_successed", $this->_user);
  164. return true;
  165. }
  166. /**
  167. * 修改密码
  168. * @param string $newpassword 新密码
  169. * @param string $oldpassword 旧密码
  170. * @param bool $ignoreoldpassword 忽略旧密码
  171. * @return boolean
  172. */
  173. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  174. {
  175. if (!$this->_logined) {
  176. $this->setError('You are not logged in');
  177. return false;
  178. }
  179. //判断旧密码是否正确
  180. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  181. Db::startTrans();
  182. try {
  183. $salt = Random::alnum();
  184. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  185. $this->_user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
  186. Token::delete($this->_token);
  187. //修改密码成功的事件
  188. Hook::listen("user_changepwd_successed", $this->_user);
  189. Db::commit();
  190. } catch (Exception $e) {
  191. Db::rollback();
  192. $this->setError($e->getMessage());
  193. return false;
  194. }
  195. return true;
  196. } else {
  197. $this->setError('Password is incorrect');
  198. return false;
  199. }
  200. }
  201. /**
  202. * 直接登录账号
  203. * @param int $user_id
  204. * @return boolean
  205. */
  206. public function direct($user_id)
  207. {
  208. $user = Coach::get($user_id);
  209. if ($user) {
  210. Db::startTrans();
  211. try {
  212. $ip = request()->ip();
  213. $time = time();
  214. //判断连续登录和最大连续登录
  215. if ($user->logintime < \fast\Date::unixtime('day')) {
  216. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  217. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  218. }
  219. $user->prevtime = $user->logintime;
  220. //记录本次登录的IP和时间
  221. $user->loginip = $ip;
  222. $user->logintime = $time;
  223. //重置登录失败次数
  224. $user->loginfailure = 0;
  225. $user->save();
  226. $this->_user = $user;
  227. $this->_token = Random::uuid();
  228. Tokencoach::set($this->_token, $user->id, $this->keeptime);
  229. $this->_logined = true;
  230. //登录成功的事件
  231. Hook::listen("user_login_successed", $this->_user);
  232. Db::commit();
  233. } catch (Exception $e) {
  234. Db::rollback();
  235. $this->setError($e->getMessage());
  236. return false;
  237. }
  238. return true;
  239. } else {
  240. return false;
  241. }
  242. }
  243. /**
  244. * 判断是否登录
  245. * @return boolean
  246. */
  247. public function isLogin()
  248. {
  249. if ($this->_logined) {
  250. return true;
  251. }
  252. return false;
  253. }
  254. /**
  255. * 获取当前Token
  256. * @return string
  257. */
  258. public function getToken()
  259. {
  260. return $this->_token;
  261. }
  262. /**
  263. * 获取会员基本信息
  264. */
  265. public function getUserinfo()
  266. {
  267. $data = $this->_user->toArray();
  268. $allowFields = $this->getAllowFields();
  269. $userinfo = array_intersect_key($data, array_flip($allowFields));
  270. $userinfo = array_merge($userinfo, Tokencoach::get($this->_token));
  271. //追加
  272. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  273. return $userinfo;
  274. }
  275. /**
  276. * 获取当前请求的URI
  277. * @return string
  278. */
  279. public function getRequestUri()
  280. {
  281. return $this->requestUri;
  282. }
  283. /**
  284. * 设置当前请求的URI
  285. * @param string $uri
  286. */
  287. public function setRequestUri($uri)
  288. {
  289. $this->requestUri = $uri;
  290. }
  291. /**
  292. * 获取允许输出的字段
  293. * @return array
  294. */
  295. public function getAllowFields()
  296. {
  297. return $this->allowFields;
  298. }
  299. /**
  300. * 设置允许输出的字段
  301. * @param array $fields
  302. */
  303. public function setAllowFields($fields)
  304. {
  305. $this->allowFields = $fields;
  306. }
  307. /**
  308. * 获取密码加密后的字符串
  309. * @param string $password 密码
  310. * @param string $salt 密码盐
  311. * @return string
  312. */
  313. public function getEncryptPassword($password, $salt = '')
  314. {
  315. return md5(md5($password) . $salt);
  316. }
  317. /**
  318. * 检测当前控制器和方法是否匹配传递的数组
  319. *
  320. * @param array $arr 需要验证权限的数组
  321. * @return boolean
  322. */
  323. public function match($arr = [])
  324. {
  325. $request = Request::instance();
  326. $arr = is_array($arr) ? $arr : explode(',', $arr);
  327. if (!$arr) {
  328. return false;
  329. }
  330. $arr = array_map('strtolower', $arr);
  331. // 是否存在
  332. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  333. return true;
  334. }
  335. // 没找到匹配
  336. return false;
  337. }
  338. /**
  339. * 设置会话有效时间
  340. * @param int $keeptime 默认为永久
  341. */
  342. public function keeptime($keeptime = 0)
  343. {
  344. $this->keeptime = $keeptime;
  345. }
  346. /**
  347. * 渲染用户数据
  348. * @param array $datalist 二维数组
  349. * @param mixed $fields 加载的字段列表
  350. * @param string $fieldkey 渲染的字段
  351. * @param string $renderkey 结果字段
  352. * @return array
  353. */
  354. /*public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  355. {
  356. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  357. $ids = [];
  358. foreach ($datalist as $k => $v) {
  359. if (!isset($v[$fieldkey])) {
  360. continue;
  361. }
  362. $ids[] = $v[$fieldkey];
  363. }
  364. $list = [];
  365. if ($ids) {
  366. if (!in_array('id', $fields)) {
  367. $fields[] = 'id';
  368. }
  369. $ids = array_unique($ids);
  370. $selectlist = User::where('id', 'in', $ids)->column($fields);
  371. foreach ($selectlist as $k => $v) {
  372. $list[$v['id']] = $v;
  373. }
  374. }
  375. foreach ($datalist as $k => &$v) {
  376. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  377. }
  378. unset($v);
  379. return $datalist;
  380. }*/
  381. /**
  382. * 设置错误信息
  383. *
  384. * @param string $error 错误信息
  385. * @return Auth
  386. */
  387. public function setError($error)
  388. {
  389. $this->_error = $error;
  390. return $this;
  391. }
  392. /**
  393. * 获取错误信息
  394. * @return string
  395. */
  396. public function getError()
  397. {
  398. return $this->_error ? __($this->_error) : '';
  399. }
  400. }