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', 'name', 'logo','image','contacts', 'mobile','province_name','city_name','area_name','province_id','city_id','area_id','address','full_address','longitude','latitude','aptitude_images','open_hours','staff'];
  26. protected $allowFields = ['id','type','truename','mobile'];
  27. public function __construct($options = [])
  28. {
  29. if ($config = Config::get('coach')) {
  30. $this->config = array_merge($this->config, $config);
  31. }
  32. $this->options = array_merge($this->config, $options);
  33. }
  34. /**
  35. *
  36. * @param array $options 参数
  37. * @return Auth
  38. */
  39. public static function instance($options = [])
  40. {
  41. if (is_null(self::$instance)) {
  42. self::$instance = new static($options);
  43. }
  44. return self::$instance;
  45. }
  46. /**
  47. * 生成不重复的随机数字字母组合
  48. */
  49. function getUinqueNo($length = 8, $nos = [])
  50. {
  51. $newid = Random::build("alnum", $length);
  52. if (in_array($newid, $nos)) {
  53. $newid = $this->getUinqueNo($length, $nos);
  54. }
  55. return $newid;
  56. }
  57. /**
  58. * 获取User模型
  59. * @return User
  60. */
  61. public function getUser()
  62. {
  63. return $this->_user;
  64. }
  65. /**
  66. * 兼容调用user模型的属性
  67. *
  68. * @param string $name
  69. * @return mixed
  70. */
  71. public function __get($name)
  72. {
  73. return $this->_user ? $this->_user->$name : null;
  74. }
  75. /**
  76. * 兼容调用user模型的属性
  77. */
  78. public function __isset($name)
  79. {
  80. return isset($this->_user) ? isset($this->_user->$name) : false;
  81. }
  82. /**
  83. * 根据Token初始化
  84. *
  85. * @param string $token Token
  86. * @return boolean
  87. */
  88. public function init($token)
  89. {
  90. if ($this->_logined) {
  91. return true;
  92. }
  93. if ($this->_error) {
  94. return false;
  95. }
  96. $data = Tokencoach::get($token);
  97. if (!$data) {
  98. return false;
  99. }
  100. $user_id = intval($data['user_id']);
  101. if ($user_id > 0) {
  102. $user = Coach::get($user_id);
  103. if (!$user) {
  104. $this->setError('Account not exist');
  105. return false;
  106. }
  107. if ($user->status != 1) {
  108. $this->setError('Account is locked');
  109. return false;
  110. }
  111. /* if(!$user->company_id){
  112. $this->setError('Account not exist');
  113. return false;
  114. }
  115. $companyinfo = Company::get($user->company_id);
  116. if(!$companyinfo){
  117. $this->setError('Account not exist');
  118. return false;
  119. }
  120. $user->company = $companyinfo;*/
  121. $this->_user = $user;
  122. $this->_logined = true;
  123. $this->_token = $token;
  124. //初始化成功的事件
  125. // Hook::listen("company_init_successed", $this->_user);
  126. return true;
  127. } else {
  128. $this->setError('You are not logged in');
  129. return false;
  130. }
  131. }
  132. /**
  133. * 用户登录
  134. *
  135. * @param string $account 账号,用户名、邮箱、手机号
  136. * @param string $password 密码
  137. * @return boolean
  138. */
  139. public function login($account, $password)
  140. {
  141. $field = 'email';
  142. $user = Coach::get([$field => $account]);
  143. if (!$user) {
  144. $this->setError('Account is incorrect');
  145. return false;
  146. }
  147. if ($user->status != 1) {
  148. $this->setError('Account is locked');
  149. return false;
  150. }
  151. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  152. $this->setError('Password is incorrect');
  153. return false;
  154. }
  155. //直接登录员工
  156. return $this->direct($user->id);
  157. }
  158. /**
  159. * 退出
  160. *
  161. * @return boolean
  162. */
  163. public function logout()
  164. {
  165. if (!$this->_logined) {
  166. $this->setError('You are not logged in');
  167. return false;
  168. }
  169. //设置登录标识
  170. $this->_logined = false;
  171. //删除Token
  172. Tokencoach::delete($this->_token);
  173. //退出成功的事件
  174. Hook::listen("user_logout_successed", $this->_user);
  175. return true;
  176. }
  177. /**
  178. * 直接登录账号
  179. * @param int $user_id
  180. * @return boolean
  181. */
  182. public function direct($user_id)
  183. {
  184. $user = Coach::get($user_id);
  185. if ($user) {
  186. Db::startTrans();
  187. try {
  188. $ip = request()->ip();
  189. $time = time();
  190. //判断连续登录和最大连续登录
  191. if ($user->logintime < \fast\Date::unixtime('day')) {
  192. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  193. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  194. }
  195. $user->prevtime = $user->logintime;
  196. //记录本次登录的IP和时间
  197. $user->loginip = $ip;
  198. $user->logintime = $time;
  199. //重置登录失败次数
  200. $user->loginfailure = 0;
  201. $user->save();
  202. $this->_user = $user;
  203. $this->_token = Random::uuid();
  204. Tokencoach::set($this->_token, $user->id, $this->keeptime);
  205. $this->_logined = true;
  206. //登录成功的事件
  207. Hook::listen("user_login_successed", $this->_user);
  208. Db::commit();
  209. } catch (Exception $e) {
  210. Db::rollback();
  211. $this->setError($e->getMessage());
  212. return false;
  213. }
  214. return true;
  215. } else {
  216. return false;
  217. }
  218. }
  219. /**
  220. * 判断是否登录
  221. * @return boolean
  222. */
  223. public function isLogin()
  224. {
  225. if ($this->_logined) {
  226. return true;
  227. }
  228. return false;
  229. }
  230. /**
  231. * 获取当前Token
  232. * @return string
  233. */
  234. public function getToken()
  235. {
  236. return $this->_token;
  237. }
  238. /**
  239. * 获取会员基本信息
  240. */
  241. public function getUserinfo()
  242. {
  243. $data = $this->_user->toArray();
  244. $allowFields = $this->getAllowFields();
  245. $userinfo = array_intersect_key($data, array_flip($allowFields));
  246. $userinfo = array_merge($userinfo, Tokencoach::get($this->_token));
  247. //追加
  248. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  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. }