Authcoach.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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','firstname','lastname', 'mobile', 'email', 'avatar','whatsapp'];
  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 = 'email';
  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 int $user_id
  169. * @return boolean
  170. */
  171. public function direct($user_id)
  172. {
  173. $user = Coach::get($user_id);
  174. if ($user) {
  175. Db::startTrans();
  176. try {
  177. $ip = request()->ip();
  178. $time = time();
  179. //判断连续登录和最大连续登录
  180. if ($user->logintime < \fast\Date::unixtime('day')) {
  181. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  182. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  183. }
  184. $user->prevtime = $user->logintime;
  185. //记录本次登录的IP和时间
  186. $user->loginip = $ip;
  187. $user->logintime = $time;
  188. //重置登录失败次数
  189. $user->loginfailure = 0;
  190. $user->save();
  191. $this->_user = $user;
  192. $this->_token = Random::uuid();
  193. Tokencoach::set($this->_token, $user->id, $this->keeptime);
  194. $this->_logined = true;
  195. //登录成功的事件
  196. Hook::listen("user_login_successed", $this->_user);
  197. Db::commit();
  198. } catch (Exception $e) {
  199. Db::rollback();
  200. $this->setError($e->getMessage());
  201. return false;
  202. }
  203. return true;
  204. } else {
  205. return false;
  206. }
  207. }
  208. /**
  209. * 判断是否登录
  210. * @return boolean
  211. */
  212. public function isLogin()
  213. {
  214. if ($this->_logined) {
  215. return true;
  216. }
  217. return false;
  218. }
  219. /**
  220. * 获取当前Token
  221. * @return string
  222. */
  223. public function getToken()
  224. {
  225. return $this->_token;
  226. }
  227. /**
  228. * 获取会员基本信息
  229. */
  230. public function getUserinfo()
  231. {
  232. $data = $this->_user->toArray();
  233. $allowFields = $this->getAllowFields();
  234. $userinfo = array_intersect_key($data, array_flip($allowFields));
  235. $userinfo = array_merge($userinfo, Tokencoach::get($this->_token));
  236. //追加
  237. $userinfo['avatar'] = one_domain_image($userinfo['avatar']);
  238. $userinfo['role_type'] = 'coach';//角色:教练
  239. return $userinfo;
  240. }
  241. /**
  242. * 获取当前请求的URI
  243. * @return string
  244. */
  245. public function getRequestUri()
  246. {
  247. return $this->requestUri;
  248. }
  249. /**
  250. * 设置当前请求的URI
  251. * @param string $uri
  252. */
  253. public function setRequestUri($uri)
  254. {
  255. $this->requestUri = $uri;
  256. }
  257. /**
  258. * 获取允许输出的字段
  259. * @return array
  260. */
  261. public function getAllowFields()
  262. {
  263. return $this->allowFields;
  264. }
  265. /**
  266. * 设置允许输出的字段
  267. * @param array $fields
  268. */
  269. public function setAllowFields($fields)
  270. {
  271. $this->allowFields = $fields;
  272. }
  273. /**
  274. * 获取密码加密后的字符串
  275. * @param string $password 密码
  276. * @param string $salt 密码盐
  277. * @return string
  278. */
  279. public function getEncryptPassword($password, $salt = '')
  280. {
  281. return md5(md5($password) . $salt);
  282. }
  283. /**
  284. * 检测当前控制器和方法是否匹配传递的数组
  285. *
  286. * @param array $arr 需要验证权限的数组
  287. * @return boolean
  288. */
  289. public function match($arr = [])
  290. {
  291. $request = Request::instance();
  292. $arr = is_array($arr) ? $arr : explode(',', $arr);
  293. if (!$arr) {
  294. return false;
  295. }
  296. $arr = array_map('strtolower', $arr);
  297. // 是否存在
  298. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  299. return true;
  300. }
  301. // 没找到匹配
  302. return false;
  303. }
  304. /**
  305. * 设置会话有效时间
  306. * @param int $keeptime 默认为永久
  307. */
  308. public function keeptime($keeptime = 0)
  309. {
  310. $this->keeptime = $keeptime;
  311. }
  312. /**
  313. * 渲染用户数据
  314. * @param array $datalist 二维数组
  315. * @param mixed $fields 加载的字段列表
  316. * @param string $fieldkey 渲染的字段
  317. * @param string $renderkey 结果字段
  318. * @return array
  319. */
  320. /*public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  321. {
  322. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  323. $ids = [];
  324. foreach ($datalist as $k => $v) {
  325. if (!isset($v[$fieldkey])) {
  326. continue;
  327. }
  328. $ids[] = $v[$fieldkey];
  329. }
  330. $list = [];
  331. if ($ids) {
  332. if (!in_array('id', $fields)) {
  333. $fields[] = 'id';
  334. }
  335. $ids = array_unique($ids);
  336. $selectlist = User::where('id', 'in', $ids)->column($fields);
  337. foreach ($selectlist as $k => $v) {
  338. $list[$v['id']] = $v;
  339. }
  340. }
  341. foreach ($datalist as $k => &$v) {
  342. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  343. }
  344. unset($v);
  345. return $datalist;
  346. }*/
  347. /**
  348. * 设置错误信息
  349. *
  350. * @param string $error 错误信息
  351. * @return Auth
  352. */
  353. public function setError($error)
  354. {
  355. $this->_error = $error;
  356. return $this;
  357. }
  358. /**
  359. * 获取错误信息
  360. * @return string
  361. */
  362. public function getError()
  363. {
  364. return $this->_error ? __($this->_error) : '';
  365. }
  366. }