Login.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2025 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\service\passport;
  13. use app\api\model\{Setting as SettingModel, UploadFile as UploadFileModel, User as UserModel};
  14. use app\api\service\{passport\Party as PartyService, user\Oauth as OauthService};
  15. use app\api\validate\passport\Login as ValidateLogin;
  16. use app\common\enum\Client as ClientEnum;
  17. use app\common\enum\Setting as SettingEnum;
  18. use app\common\service\BaseService;
  19. use cores\exception\BaseException;
  20. use think\facade\Cache;
  21. /**
  22. * 服务类:用户登录
  23. * Class Login
  24. * @package app\api\service\passport
  25. */
  26. class Login extends BaseService
  27. {
  28. /**
  29. * 用户信息 (登录成功后才记录)
  30. * @var UserModel|null $userInfo
  31. */
  32. private ?UserModel $userInfo;
  33. // 用于生成token的自定义盐
  34. const TOKEN_SALT = 'user_salt';
  35. // 同一手机号允许的连续登录失败次数
  36. const LOGIN_FAIL_LIMIT = 5;
  37. // 登录失败锁定时间 (秒)
  38. const LOGIN_FAIL_LOCK_TIME = 600;
  39. /**
  40. * 执行用户登录 (手机号 + 密码)
  41. * @param array $data
  42. * @return bool
  43. * @throws BaseException
  44. * @throws \think\Exception
  45. * @throws \think\db\exception\DataNotFoundException
  46. * @throws \think\db\exception\DbException
  47. * @throws \think\db\exception\ModelNotFoundException
  48. */
  49. public function login(array $data): bool
  50. {
  51. // 数据验证
  52. $this->validate($data);
  53. // 兜底: 第三方用户信息 (非必填)
  54. $data = \array_merge(['isParty' => false, 'partyData' => []], $data);
  55. // 手机号 + 密码登录 (未注册的手机号自动注册)
  56. $this->loginByPassword($data['mobile'], $data['password'], $data['isParty'], $data['partyData']);
  57. // 保存第三方用户信息
  58. $this->createUserOauth($this->getUserId(), $data['isParty'], $data['partyData']);
  59. // 记录登录态
  60. return $this->setSession();
  61. }
  62. /**
  63. * 快捷登录:微信小程序用户
  64. * @param array $form
  65. * @return bool
  66. * @throws BaseException
  67. * @throws \think\db\exception\DataNotFoundException
  68. * @throws \think\db\exception\DbException
  69. * @throws \think\db\exception\ModelNotFoundException
  70. * @throws \think\Exception
  71. */
  72. public function loginMpWx(array $form): bool
  73. {
  74. // 获取微信小程序登录态(session)
  75. $wxSession = PartyService::getMpWxSession($form['partyData']['code']);
  76. // 判断openid是否存在
  77. $userId = OauthService::getUserIdByOauthId($wxSession['openid'], ClientEnum::MP_WEIXIN);
  78. // 获取用户信息
  79. $userInfo = !empty($userId) ? UserModel::detail($userId) : null;
  80. // 用户信息存在, 更新登录信息
  81. if (!empty($userInfo)) {
  82. // 更新用户登录信息
  83. $this->updateUser($userInfo, true, $form['partyData']);
  84. // 记录登录态
  85. return $this->setSession();
  86. }
  87. // 用户信息不存在 => 注册新用户 或者 跳转到绑定手机号页
  88. $setting = SettingModel::getItem(SettingEnum::REGISTER);
  89. // 后台设置了需强制绑定手机号, 返回前端isBindMobile, 跳转到手机号验证页
  90. if ($setting['isForceBindMpweixin']) {
  91. throwError('当前用户未绑定手机号', null, ['isBindMobile' => true, 'isPrompt' => false]);
  92. }
  93. // 后台未开启强制绑定手机号, 直接保存新用户
  94. if (!$setting['isForceBindMpweixin']) {
  95. // 用户不存在: 创建一个新用户
  96. $this->createUser('', true, $form['partyData']);
  97. // 保存第三方用户信息
  98. $this->createUserOauth($this->getUserId(), true, $form['partyData']);
  99. }
  100. // 记录登录态
  101. return $this->setSession();
  102. }
  103. /**
  104. * 是否需要填写昵称头像 (微信小程序端)
  105. * @param string $code
  106. * @return bool
  107. * @throws BaseException
  108. * @throws \think\db\exception\DataNotFoundException
  109. * @throws \think\db\exception\DbException
  110. * @throws \think\db\exception\ModelNotFoundException
  111. * @throws \think\Exception
  112. */
  113. public function isPersonalMpweixin(string $code): bool
  114. {
  115. // 后台需开启填写微信头像和昵称
  116. $setting = SettingModel::getItem(SettingEnum::REGISTER);
  117. if (!$setting['isPersonalMpweixin']) {
  118. return false;
  119. }
  120. // 获取微信小程序登录态 (session)
  121. $wxSession = PartyService::getMpWxSession($code);
  122. // 判断用户是否存在 (openid)
  123. return !OauthService::getUserIdByOauthId($wxSession['openid'], ClientEnum::MP_WEIXIN);
  124. }
  125. /**
  126. * 快捷登录:微信小程序授权手机号登录
  127. * @param array $form
  128. * @return bool
  129. * @throws BaseException
  130. * @throws \think\db\exception\DataNotFoundException
  131. * @throws \think\db\exception\DbException
  132. * @throws \think\db\exception\ModelNotFoundException
  133. * @throws \think\Exception
  134. */
  135. public function loginMpWxMobile(array $form): bool
  136. {
  137. // 获取微信小程序登录态(session)
  138. $wxSession = PartyService::getMpWxSession($form['code']);
  139. // 解密encryptedData -> 拿到手机号
  140. $plainData = OauthService::wxDecryptData($form['encryptedData'], $form['iv'], $wxSession['session_key']);
  141. // 整理登录注册数据
  142. $loginData = [
  143. 'mobile' => $plainData['purePhoneNumber'],
  144. 'isParty' => $form['isParty'],
  145. 'partyData' => $form['partyData'],
  146. ];
  147. // 自动登录注册
  148. $this->register($loginData);
  149. // 保存第三方用户信息
  150. $this->createUserOauth($this->getUserId(), $loginData['isParty'], $loginData['partyData']);
  151. // 记录登录态
  152. return $this->setSession();
  153. }
  154. /**
  155. * 保存oauth信息(第三方用户信息)
  156. * @param int $userId 用户ID
  157. * @param bool $isParty 是否为第三方用户
  158. * @param array $partyData 第三方用户数据
  159. * @return void
  160. * @throws BaseException
  161. * @throws \think\db\exception\DataNotFoundException
  162. * @throws \think\db\exception\DbException
  163. * @throws \think\db\exception\ModelNotFoundException
  164. */
  165. private function createUserOauth(int $userId, bool $isParty, array $partyData = []): void
  166. {
  167. if ($isParty) {
  168. $Oauth = new PartyService;
  169. $Oauth->createUserOauth($userId, $partyData);
  170. }
  171. }
  172. /**
  173. * 当前登录的用户信息
  174. * @return UserModel
  175. */
  176. public function getUserInfo(): UserModel
  177. {
  178. return $this->userInfo;
  179. }
  180. /**
  181. * 当前登录的用户ID
  182. * @return int
  183. */
  184. private function getUserId(): int
  185. {
  186. return (int)$this->getUserInfo()['user_id'];
  187. }
  188. /**
  189. * 手机号 + 密码登录
  190. * 1. 用户不存在: 自动注册并设置密码 (与页面文案“未注册的手机号登录后将自动注册”一致)
  191. * 2. 用户存在但未设置密码: 本次输入的密码作为初始密码 (兼容历史短信登录的老用户)
  192. * 3. 用户已设置密码: 校验密码, 失败累计次数并锁定
  193. * @param string $mobile 手机号
  194. * @param string $password 登录密码(明文)
  195. * @param bool $isParty 是否存在第三方用户信息
  196. * @param array $partyData 第三方用户数据
  197. * @return void
  198. * @throws BaseException
  199. * @throws \think\Exception
  200. * @throws \think\db\exception\DataNotFoundException
  201. * @throws \think\db\exception\DbException
  202. * @throws \think\db\exception\ModelNotFoundException
  203. */
  204. private function loginByPassword(string $mobile, string $password, bool $isParty, array $partyData = []): void
  205. {
  206. // 查询用户是否已存在
  207. $userInfo = UserModel::detail(['mobile' => $mobile]);
  208. // 用户不存在: 注册新用户并设置密码
  209. if (empty($userInfo)) {
  210. $this->createUser($mobile, $isParty, $partyData, $password);
  211. return;
  212. }
  213. // 用户已存在但尚未设置密码: 本次输入的密码作为初始密码
  214. if (!$userInfo->hasPassword()) {
  215. $this->updateUser($userInfo, $isParty, $partyData, $password);
  216. return;
  217. }
  218. // 是否已被锁定
  219. $this->checkLoginFailTimes($mobile);
  220. // 校验密码
  221. if (!$userInfo->verifyPassword($password)) {
  222. $this->recordLoginFail($mobile);
  223. throwError('手机号或密码不正确');
  224. }
  225. // 登录成功, 清空失败记录
  226. Cache::delete($this->getLoginFailCacheKey($mobile));
  227. // 更新用户登录信息
  228. $this->updateUser($userInfo, $isParty, $partyData);
  229. }
  230. /**
  231. * 登录失败次数缓存的key
  232. * @param string $mobile
  233. * @return string
  234. */
  235. private function getLoginFailCacheKey(string $mobile): string
  236. {
  237. return 'login_fail_' . md5("{$this->storeId}_{$mobile}");
  238. }
  239. /**
  240. * 检查登录失败次数 (超出限制则锁定)
  241. * @param string $mobile
  242. * @return void
  243. * @throws BaseException
  244. */
  245. private function checkLoginFailTimes(string $mobile): void
  246. {
  247. $times = (int)Cache::get($this->getLoginFailCacheKey($mobile), 0);
  248. if ($times >= self::LOGIN_FAIL_LIMIT) {
  249. $minutes = (int)(self::LOGIN_FAIL_LOCK_TIME / 60);
  250. \throwError("密码错误次数过多, 请{$minutes}分钟后再试");
  251. }
  252. }
  253. /**
  254. * 记录一次登录失败
  255. * @param string $mobile
  256. * @return void
  257. */
  258. private function recordLoginFail(string $mobile): void
  259. {
  260. $key = $this->getLoginFailCacheKey($mobile);
  261. $times = (int)Cache::get($key, 0) + 1;
  262. Cache::set($key, $times, self::LOGIN_FAIL_LOCK_TIME);
  263. }
  264. /**
  265. * 自动登录注册 (第三方/授权手机号登录, 无需密码)
  266. * @param array $data
  267. * @throws BaseException
  268. * @throws \think\Exception
  269. * @throws \think\db\exception\DataNotFoundException
  270. * @throws \think\db\exception\DbException
  271. * @throws \think\db\exception\ModelNotFoundException
  272. */
  273. private function register(array $data): void
  274. {
  275. // 查询用户是否已存在
  276. // 用户存在: 更新用户登录信息
  277. $userInfo = UserModel::detail(['mobile' => $data['mobile']]);
  278. if ($userInfo) {
  279. $this->updateUser($userInfo, $data['isParty'], $data['partyData']);
  280. return;
  281. }
  282. // 用户不存在: 创建一个新用户
  283. $this->createUser($data['mobile'], $data['isParty'], $data['partyData']);
  284. }
  285. /**
  286. * 新增用户
  287. * @param string $mobile 手机号
  288. * @param bool $isParty 是否存在第三方用户信息
  289. * @param array $partyData 用户信息(第三方)
  290. * @param string $password 登录密码(明文, 为空则不设置)
  291. * @return void
  292. * @throws \think\Exception
  293. * @throws \think\db\exception\DataNotFoundException
  294. * @throws \think\db\exception\DbException
  295. * @throws \think\db\exception\ModelNotFoundException
  296. */
  297. private function createUser(string $mobile, bool $isParty, array $partyData = [], string $password = ''): void
  298. {
  299. // 用户信息
  300. $data = [
  301. 'mobile' => $mobile,
  302. 'nick_name' => !empty($mobile) ? \hide_mobile($mobile) : '',
  303. 'platform' => \getPlatform(),
  304. 'last_login_time' => \time(),
  305. 'store_id' => $this->storeId
  306. ];
  307. // 登录密码 (模型修改器会自动使用 password_hash 加密)
  308. if ($password !== '') {
  309. $data['password'] = $password;
  310. }
  311. // 写入用户信息(第三方)
  312. if ($isParty === true && !empty($partyData)) {
  313. $partyUserInfo = PartyService::partyUserInfo($partyData, true);
  314. $data = \array_merge($data, $partyUserInfo);
  315. }
  316. // 新增用户记录
  317. $model = new UserModel;
  318. $model->save($data);
  319. // 将微信用户昵称添加编号便于后台管理, 例如:微信用户_10001
  320. if (\in_array($data['nick_name'], ['微信用户', '支付宝用户'])) {
  321. $model->save(['nick_name' => "{$data['nick_name']}_{$model['user_id']}"]);
  322. }
  323. // 记录头像文件上传者
  324. if (isset($data['avatar_id']) && $data['avatar_id'] > 0) {
  325. UploadFileModel::setUploaderId($data['avatar_id'], (int)$model['user_id']);
  326. }
  327. // 记录用户信息
  328. $this->userInfo = $model;
  329. }
  330. /**
  331. * 更新用户登录信息
  332. * @param UserModel $userInfo
  333. * @param bool $isParty 是否存在第三方用户信息
  334. * @param array $partyData 用户信息(第三方)
  335. * @param string $password 登录密码(明文, 为空则不更新)
  336. */
  337. private function updateUser(UserModel $userInfo, bool $isParty, array $partyData = [], string $password = ''): void
  338. {
  339. // 用户信息
  340. $data = [
  341. 'last_login_time' => \time(),
  342. 'store_id' => $this->storeId
  343. ];
  344. // 设置/更新登录密码 (模型修改器会自动使用 password_hash 加密)
  345. if ($password !== '') {
  346. $data['password'] = $password;
  347. }
  348. // 写入用户信息(第三方)
  349. // 如果不需要每次登录都更新微信用户头像昵称, 下面几行代码可以屏蔽掉
  350. // if ($isParty === true && !empty($partyData)) {
  351. // $partyUserInfo = PartyService::partyUserInfo($partyData);
  352. // $data = \array_merge($data, $partyUserInfo);
  353. // }
  354. // // 记录头像文件上传者
  355. // if (isset($data['avatar_id']) && $data['avatar_id'] > 0) {
  356. // UploadFileModel::setUploaderId($data['avatar_id'], $userInfo['user_id']);
  357. // }
  358. // 更新用户记录
  359. $userInfo->save($data);
  360. // 记录用户信息
  361. $this->userInfo = $userInfo;
  362. }
  363. /**
  364. * 记录登录态
  365. * @return bool
  366. * @throws BaseException
  367. */
  368. private function setSession(): bool
  369. {
  370. empty($this->userInfo) && \throwError('未找到用户信息');
  371. // 登录的token
  372. $token = $this->getToken($this->getUserId());
  373. // 记录缓存, 30天
  374. Cache::set($token, [
  375. 'user' => $this->userInfo,
  376. 'store_id' => $this->storeId,
  377. 'is_login' => true,
  378. ], 86400 * 30);
  379. return true;
  380. }
  381. /**
  382. * 数据验证
  383. * @param array $data
  384. * @return void
  385. * @throws BaseException
  386. */
  387. private function validate(array $data): void
  388. {
  389. // 数据验证 (手机号 + 登录密码)
  390. $validate = new ValidateLogin;
  391. if (!$validate->check($data)) {
  392. throwError($validate->getError());
  393. }
  394. }
  395. /**
  396. * 获取登录的token
  397. * @param int $userId
  398. * @return string
  399. */
  400. public function getToken(int $userId): string
  401. {
  402. static $token = '';
  403. if (empty($token)) {
  404. $token = $this->makeToken($userId);
  405. }
  406. return $token;
  407. }
  408. /**
  409. * 生成用户认证的token
  410. * @param int $userId
  411. * @return string
  412. */
  413. private function makeToken(int $userId): string
  414. {
  415. $storeId = $this->storeId;
  416. // 生成一个不会重复的随机字符串
  417. $guid = \get_guid_v4();
  418. // 当前时间戳 (精确到毫秒)
  419. $timeStamp = \microtime(true);
  420. // 自定义一个盐
  421. $salt = self::TOKEN_SALT;
  422. return md5("{$storeId}_{$timeStamp}_{$userId}_{$guid}_{$salt}");
  423. }
  424. }