Authcoach.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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', '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. /* if(!$user->company_id){
  111. $this->setError('Account not exist');
  112. return false;
  113. }
  114. $companyinfo = Company::get($user->company_id);
  115. if(!$companyinfo){
  116. $this->setError('Account not exist');
  117. return false;
  118. }
  119. $user->company = $companyinfo;*/
  120. $this->_user = $user;
  121. $this->_logined = true;
  122. $this->_token = $token;
  123. //初始化成功的事件
  124. // Hook::listen("company_init_successed", $this->_user);
  125. return true;
  126. } else {
  127. $this->setError('You are not logged in');
  128. return false;
  129. }
  130. }
  131. /**
  132. * 用户登录
  133. *
  134. * @param string $account 账号,用户名、邮箱、手机号
  135. * @param string $password 密码
  136. * @return boolean
  137. */
  138. public function login($account, $password)
  139. {
  140. $field = 'email';
  141. $user = Coach::get([$field => $account]);
  142. if (!$user) {
  143. $this->setError('Account is incorrect');
  144. return false;
  145. }
  146. if ($user->status != 1) {
  147. $this->setError('Account is locked');
  148. return false;
  149. }
  150. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  151. $this->setError('Password is incorrect');
  152. return false;
  153. }
  154. //直接登录员工
  155. return $this->direct($user->id);
  156. }
  157. /**
  158. * 退出
  159. *
  160. * @return boolean
  161. */
  162. public function logout()
  163. {
  164. if (!$this->_logined) {
  165. $this->setError('You are not logged in');
  166. return false;
  167. }
  168. //设置登录标识
  169. $this->_logined = false;
  170. //删除Token
  171. Tokencoach::delete($this->_token);
  172. //退出成功的事件
  173. Hook::listen("user_logout_successed", $this->_user);
  174. return true;
  175. }
  176. /**
  177. * 直接登录账号
  178. * @param int $user_id
  179. * @return boolean
  180. */
  181. public function direct($user_id)
  182. {
  183. $user = Coach::get($user_id);
  184. if ($user) {
  185. Db::startTrans();
  186. try {
  187. $ip = request()->ip();
  188. $time = time();
  189. //判断连续登录和最大连续登录
  190. if ($user->logintime < \fast\Date::unixtime('day')) {
  191. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  192. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  193. }
  194. $user->prevtime = $user->logintime;
  195. //记录本次登录的IP和时间
  196. $user->loginip = $ip;
  197. $user->logintime = $time;
  198. //重置登录失败次数
  199. $user->loginfailure = 0;
  200. $user->save();
  201. $this->_user = $user;
  202. $this->_token = Random::uuid();
  203. Tokencoach::set($this->_token, $user->id, $this->keeptime);
  204. $this->_logined = true;
  205. //登录成功的事件
  206. Hook::listen("user_login_successed", $this->_user);
  207. Db::commit();
  208. } catch (Exception $e) {
  209. Db::rollback();
  210. $this->setError($e->getMessage());
  211. return false;
  212. }
  213. return true;
  214. } else {
  215. return false;
  216. }
  217. }
  218. /**
  219. * 判断是否登录
  220. * @return boolean
  221. */
  222. public function isLogin()
  223. {
  224. if ($this->_logined) {
  225. return true;
  226. }
  227. return false;
  228. }
  229. /**
  230. * 获取当前Token
  231. * @return string
  232. */
  233. public function getToken()
  234. {
  235. return $this->_token;
  236. }
  237. /**
  238. * 获取会员基本信息
  239. */
  240. public function getUserinfo()
  241. {
  242. $data = $this->_user->toArray();
  243. $allowFields = $this->getAllowFields();
  244. $userinfo = array_intersect_key($data, array_flip($allowFields));
  245. $userinfo = array_merge($userinfo, Tokencoach::get($this->_token));
  246. //追加
  247. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  248. return $userinfo;
  249. }
  250. /**
  251. * 获取当前请求的URI
  252. * @return string
  253. */
  254. public function getRequestUri()
  255. {
  256. return $this->requestUri;
  257. }
  258. /**
  259. * 设置当前请求的URI
  260. * @param string $uri
  261. */
  262. public function setRequestUri($uri)
  263. {
  264. $this->requestUri = $uri;
  265. }
  266. /**
  267. * 获取允许输出的字段
  268. * @return array
  269. */
  270. public function getAllowFields()
  271. {
  272. return $this->allowFields;
  273. }
  274. /**
  275. * 设置允许输出的字段
  276. * @param array $fields
  277. */
  278. public function setAllowFields($fields)
  279. {
  280. $this->allowFields = $fields;
  281. }
  282. /**
  283. * 获取密码加密后的字符串
  284. * @param string $password 密码
  285. * @param string $salt 密码盐
  286. * @return string
  287. */
  288. public function getEncryptPassword($password, $salt = '')
  289. {
  290. return md5(md5($password) . $salt);
  291. }
  292. /**
  293. * 检测当前控制器和方法是否匹配传递的数组
  294. *
  295. * @param array $arr 需要验证权限的数组
  296. * @return boolean
  297. */
  298. public function match($arr = [])
  299. {
  300. $request = Request::instance();
  301. $arr = is_array($arr) ? $arr : explode(',', $arr);
  302. if (!$arr) {
  303. return false;
  304. }
  305. $arr = array_map('strtolower', $arr);
  306. // 是否存在
  307. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  308. return true;
  309. }
  310. // 没找到匹配
  311. return false;
  312. }
  313. /**
  314. * 设置会话有效时间
  315. * @param int $keeptime 默认为永久
  316. */
  317. public function keeptime($keeptime = 0)
  318. {
  319. $this->keeptime = $keeptime;
  320. }
  321. /**
  322. * 渲染用户数据
  323. * @param array $datalist 二维数组
  324. * @param mixed $fields 加载的字段列表
  325. * @param string $fieldkey 渲染的字段
  326. * @param string $renderkey 结果字段
  327. * @return array
  328. */
  329. /*public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  330. {
  331. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  332. $ids = [];
  333. foreach ($datalist as $k => $v) {
  334. if (!isset($v[$fieldkey])) {
  335. continue;
  336. }
  337. $ids[] = $v[$fieldkey];
  338. }
  339. $list = [];
  340. if ($ids) {
  341. if (!in_array('id', $fields)) {
  342. $fields[] = 'id';
  343. }
  344. $ids = array_unique($ids);
  345. $selectlist = User::where('id', 'in', $ids)->column($fields);
  346. foreach ($selectlist as $k => $v) {
  347. $list[$v['id']] = $v;
  348. }
  349. }
  350. foreach ($datalist as $k => &$v) {
  351. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  352. }
  353. unset($v);
  354. return $datalist;
  355. }*/
  356. /**
  357. * 设置错误信息
  358. *
  359. * @param string $error 错误信息
  360. * @return Auth
  361. */
  362. public function setError($error)
  363. {
  364. $this->_error = $error;
  365. return $this;
  366. }
  367. /**
  368. * 获取错误信息
  369. * @return string
  370. */
  371. public function getError()
  372. {
  373. return $this->_error ? __($this->_error) : '';
  374. }
  375. }