Authcoach.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. $userinfo['role_type'] = 'coach';//角色:教练
  249. return $userinfo;
  250. }
  251. /**
  252. * 获取当前请求的URI
  253. * @return string
  254. */
  255. public function getRequestUri()
  256. {
  257. return $this->requestUri;
  258. }
  259. /**
  260. * 设置当前请求的URI
  261. * @param string $uri
  262. */
  263. public function setRequestUri($uri)
  264. {
  265. $this->requestUri = $uri;
  266. }
  267. /**
  268. * 获取允许输出的字段
  269. * @return array
  270. */
  271. public function getAllowFields()
  272. {
  273. return $this->allowFields;
  274. }
  275. /**
  276. * 设置允许输出的字段
  277. * @param array $fields
  278. */
  279. public function setAllowFields($fields)
  280. {
  281. $this->allowFields = $fields;
  282. }
  283. /**
  284. * 获取密码加密后的字符串
  285. * @param string $password 密码
  286. * @param string $salt 密码盐
  287. * @return string
  288. */
  289. public function getEncryptPassword($password, $salt = '')
  290. {
  291. return md5(md5($password) . $salt);
  292. }
  293. /**
  294. * 检测当前控制器和方法是否匹配传递的数组
  295. *
  296. * @param array $arr 需要验证权限的数组
  297. * @return boolean
  298. */
  299. public function match($arr = [])
  300. {
  301. $request = Request::instance();
  302. $arr = is_array($arr) ? $arr : explode(',', $arr);
  303. if (!$arr) {
  304. return false;
  305. }
  306. $arr = array_map('strtolower', $arr);
  307. // 是否存在
  308. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  309. return true;
  310. }
  311. // 没找到匹配
  312. return false;
  313. }
  314. /**
  315. * 设置会话有效时间
  316. * @param int $keeptime 默认为永久
  317. */
  318. public function keeptime($keeptime = 0)
  319. {
  320. $this->keeptime = $keeptime;
  321. }
  322. /**
  323. * 渲染用户数据
  324. * @param array $datalist 二维数组
  325. * @param mixed $fields 加载的字段列表
  326. * @param string $fieldkey 渲染的字段
  327. * @param string $renderkey 结果字段
  328. * @return array
  329. */
  330. /*public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  331. {
  332. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  333. $ids = [];
  334. foreach ($datalist as $k => $v) {
  335. if (!isset($v[$fieldkey])) {
  336. continue;
  337. }
  338. $ids[] = $v[$fieldkey];
  339. }
  340. $list = [];
  341. if ($ids) {
  342. if (!in_array('id', $fields)) {
  343. $fields[] = 'id';
  344. }
  345. $ids = array_unique($ids);
  346. $selectlist = User::where('id', 'in', $ids)->column($fields);
  347. foreach ($selectlist as $k => $v) {
  348. $list[$v['id']] = $v;
  349. }
  350. }
  351. foreach ($datalist as $k => &$v) {
  352. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  353. }
  354. unset($v);
  355. return $datalist;
  356. }*/
  357. /**
  358. * 设置错误信息
  359. *
  360. * @param string $error 错误信息
  361. * @return Auth
  362. */
  363. public function setError($error)
  364. {
  365. $this->_error = $error;
  366. return $this;
  367. }
  368. /**
  369. * 获取错误信息
  370. * @return string
  371. */
  372. public function getError()
  373. {
  374. return $this->_error ? __($this->_error) : '';
  375. }
  376. }