Login.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 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\index\service\passport;
  13. use think\facade\Cache;
  14. use think\helper\Str;
  15. use yiovo\captcha\facade\CaptchaApi;
  16. use app\index\model\{User as UserModel, Setting as SettingModel};
  17. use app\index\service\{user\Oauth as OauthService, user\Avatar as AvatarService, passport\Party as PartyService};
  18. use app\index\validate\passport\Login as ValidateLogin;
  19. use app\common\service\BaseService;
  20. use app\common\enum\Setting as SettingEnum;
  21. use cores\exception\BaseException;
  22. /**
  23. * 服务类:用户登录
  24. * Class Login
  25. * @package app\api\service\passport
  26. */
  27. class Login extends BaseService
  28. {
  29. /**
  30. * 用户信息 (登录成功后才记录)
  31. * @var UserModel|null $userInfo
  32. */
  33. private $userInfo;
  34. // 用于生成token的自定义盐
  35. const TOKEN_SALT = 'user_salt';
  36. /**
  37. * 执行用户登录
  38. * @param array $data
  39. * @return bool
  40. * @throws BaseException
  41. * @throws \think\Exception
  42. * @throws \think\db\exception\DataNotFoundException
  43. * @throws \think\db\exception\DbException
  44. * @throws \think\db\exception\ModelNotFoundException
  45. */
  46. public function login(array $data): bool
  47. {
  48. empty($data['partyData']) && $data['partyData'] = [];
  49. if ($data['isParty'] == 'true' || $data['isParty'] === true) {
  50. $data['isParty'] = true;
  51. } else {
  52. $data['isParty'] = false;
  53. }
  54. // 数据验证
  55. $this->validate($data);
  56. // 自动登录注册
  57. $this->register($data);
  58. // 保存第三方用户信息
  59. $this->createUserOauth($this->getUserId(), $data['isParty'], $data['partyData']);
  60. // 记录登录态
  61. return $this->setSession();
  62. }
  63. public function toLogin(array $data): bool
  64. {
  65. empty($data['partyData']) && $data['partyData'] = [];
  66. if ($data['isParty'] == 'true' || $data['isParty'] === true) {
  67. $data['isParty'] = true;
  68. } else {
  69. $data['isParty'] = false;
  70. }
  71. // 数据验证
  72. $this->validate($data);
  73. // 自动登录注册
  74. $userInfo = UserModel::detail(['mobile' => $data['mobile']]);
  75. if ($userInfo) {
  76. if (md5($data['password'] . $userInfo['salt']) !== $userInfo['password']) {
  77. throwError('The account does not exist or the password is incorrect.', 500, []);
  78. }
  79. $this->updateUser($userInfo, $data['isParty'], $data['partyData']);
  80. // 保存第三方用户信息
  81. $this->createUserOauth($this->getUserId(), $data['isParty'], $data['partyData']);
  82. // 记录登录态
  83. return $this->setSession();
  84. } else {
  85. throwError('The account does not exist or the password is incorrect.', 500, []);
  86. }
  87. }
  88. public function toRegister(array $data): bool
  89. {
  90. empty($data['partyData']) && $data['partyData'] = [];
  91. if ($data['isParty'] == 'true' || $data['isParty'] === true) {
  92. $data['isParty'] = true;
  93. } else {
  94. $data['isParty'] = false;
  95. }
  96. // 数据验证
  97. $this->validate($data);
  98. $userInfo = UserModel::detail(['mobile' => $data['mobile']]);
  99. if ($userInfo) {
  100. throwError('The account you entered has already been registered.', 500, []);
  101. }
  102. // 用户不存在: 创建一个新用户
  103. $this->createUser($data['mobile'], $data['isParty'], $data['partyData'], $data['password']);
  104. return true;
  105. }
  106. /**
  107. * 快捷登录:微信小程序用户
  108. * @param array $form
  109. * @return bool
  110. * @throws BaseException
  111. * @throws \think\db\exception\DataNotFoundException
  112. * @throws \think\db\exception\DbException
  113. * @throws \think\db\exception\ModelNotFoundException
  114. * @throws \think\Exception
  115. */
  116. public function loginMpWx(array $form): bool
  117. {
  118. // 获取微信小程序登录态(session)
  119. $wxSession = PartyService::getMpWxSession($form['partyData']['code']);
  120. // 判断openid是否存在
  121. $userId = OauthService::getUserIdByOauthId($wxSession['openid'], 'MP-WEIXIN');
  122. // 获取用户信息
  123. $userInfo = !empty($userId) ? UserModel::detail($userId) : null;
  124. // 用户信息存在, 更新登录信息
  125. if (!empty($userInfo)) {
  126. // 更新用户登录信息
  127. $this->updateUser($userInfo, true, $form['partyData']);
  128. // 记录登录态
  129. return $this->setSession();
  130. }
  131. // 用户信息不存在 => 注册新用户 或者 跳转到绑定手机号页
  132. $setting = SettingModel::getItem(SettingEnum::REGISTER);
  133. // 后台设置了需强制绑定手机号, 返回前端isBindMobile, 跳转到手机号验证页
  134. if ($setting['isForceBindMpweixin']) {
  135. throwError('当前用户未绑定手机号', null, ['isBindMobile' => true]);
  136. }
  137. // 后台未开启强制绑定手机号, 直接保存新用户
  138. if (!$setting['isForceBindMpweixin']) {
  139. // 用户不存在: 创建一个新用户
  140. $this->createUser('', true, $form['partyData']);
  141. // 保存第三方用户信息
  142. $this->createUserOauth($this->getUserId(), true, $form['partyData']);
  143. }
  144. // 记录登录态
  145. return $this->setSession();
  146. }
  147. public function resetPassword($email, $smsCode, $password)
  148. {
  149. //todo 电子烟校验邮箱mobile的验证码是否匹配
  150. $mailCaptcha = new MailCaptcha();
  151. $mailCaptcha->checkCaptcha($smsCode, $email);
  152. $userInfo = !empty($email) ? UserModel::detail(['mobile' => $email]) : null;
  153. if (empty($userInfo)) {
  154. throwError('Not exit', 401, []);
  155. }
  156. $data = ['password' => md5($password . $userInfo['salt'])];
  157. // 更新用户记录
  158. return $userInfo->save($data) !== false;
  159. }
  160. /**
  161. * 快捷登录:微信小程序用户
  162. * @param array $form
  163. * @return bool
  164. * @throws BaseException
  165. * @throws \think\db\exception\DataNotFoundException
  166. * @throws \think\db\exception\DbException
  167. * @throws \think\db\exception\ModelNotFoundException
  168. * @throws \think\Exception
  169. */
  170. public function loginMpWxMobile(array $form): bool
  171. {
  172. // 获取微信小程序登录态(session)
  173. $wxSession = PartyService::getMpWxSession($form['code']);
  174. // 解密encryptedData -> 拿到手机号
  175. $wxData = OauthService::wxDecryptData($wxSession['session_key'], $form['encryptedData'], $form['iv']);
  176. // 整理登录注册数据
  177. $loginData = [
  178. 'mobile' => $wxData['purePhoneNumber'],
  179. 'isParty' => $form['isParty'],
  180. 'partyData' => $form['partyData'],
  181. ];
  182. // 自动登录注册
  183. $this->register($loginData);
  184. // 保存第三方用户信息
  185. $this->createUserOauth($this->getUserId(), $loginData['isParty'], $loginData['partyData']);
  186. // 记录登录态
  187. return $this->setSession();
  188. }
  189. /**
  190. * 保存oauth信息(第三方用户信息)
  191. * @param int $userId 用户ID
  192. * @param bool $isParty 是否为第三方用户
  193. * @param array $partyData 第三方用户数据
  194. * @return void
  195. * @throws BaseException
  196. * @throws \think\db\exception\DataNotFoundException
  197. * @throws \think\db\exception\DbException
  198. * @throws \think\db\exception\ModelNotFoundException
  199. */
  200. private function createUserOauth(int $userId, bool $isParty, array $partyData = []): void
  201. {
  202. if ($isParty) {
  203. $Oauth = new PartyService;
  204. $Oauth->createUserOauth($userId, $partyData);
  205. }
  206. }
  207. /**
  208. * 当前登录的用户信息
  209. */
  210. public function getUserInfo(): ?UserModel
  211. {
  212. return $this->userInfo;
  213. }
  214. /**
  215. * 当前登录的用户ID
  216. * @return int
  217. */
  218. private function getUserId(): int
  219. {
  220. return (int)$this->getUserInfo()['user_id'];
  221. }
  222. /**
  223. * 自动登录注册
  224. * @param array $data
  225. * @return void
  226. * @throws \think\Exception
  227. * @throws \think\db\exception\DataNotFoundException
  228. * @throws \think\db\exception\DbException
  229. * @throws \think\db\exception\ModelNotFoundException
  230. */
  231. private function register(array $data): void
  232. {
  233. // 查询用户是否已存在
  234. // 用户存在: 更新用户登录信息
  235. $userInfo = UserModel::detail(['mobile' => $data['mobile']]);
  236. if ($userInfo) {
  237. $this->updateUser($userInfo, $data['isParty'], $data['partyData']);
  238. return;
  239. }
  240. // 用户不存在: 创建一个新用户
  241. $this->createUser($data['mobile'], $data['isParty'], $data['partyData'], $data['password']);
  242. }
  243. /**
  244. * 新增用户
  245. * @param string $mobile 手机号
  246. * @param bool $isParty 是否存在第三方用户信息
  247. * @param array $partyData 用户信息(第三方)
  248. * @return void
  249. * @throws \think\Exception
  250. * @throws \think\db\exception\DataNotFoundException
  251. * @throws \think\db\exception\DbException
  252. * @throws \think\db\exception\ModelNotFoundException
  253. */
  254. private function createUser(string $mobile, bool $isParty, array $partyData = [], string $password = ''): void
  255. {
  256. $salt = Str::random(6);
  257. // 用户信息
  258. $data = [
  259. 'mobile' => $mobile,
  260. 'nick_name' => !empty($mobile) ? hide_mobile($mobile) : '',
  261. 'platform' => getPlatform(),
  262. 'last_login_time' => time(),
  263. 'store_id' => $this->storeId,
  264. 'salt' => $salt,
  265. 'password' => md5($password . $salt)
  266. ];
  267. // 写入用户信息(第三方)
  268. if ($isParty === true && !empty($partyData)) {
  269. $partyUserInfo = PartyService::partyUserInfo($partyData, true);
  270. $data = array_merge($data, $partyUserInfo);
  271. }
  272. // 新增用户记录
  273. $model = new UserModel;
  274. $status = $model->save($data);
  275. // 记录用户信息
  276. $this->userInfo = $model;
  277. }
  278. /**
  279. * 更新用户登录信息
  280. * @param UserModel $userInfo
  281. * @param bool $isParty 是否存在第三方用户信息
  282. * @param array $partyData 用户信息(第三方)
  283. * @return void
  284. */
  285. private function updateUser(UserModel $userInfo, bool $isParty, array $partyData = []): void
  286. {
  287. // 用户信息
  288. $data = [
  289. 'last_login_time' => time(),
  290. 'store_id' => $this->storeId
  291. ];
  292. // 写入用户信息(第三方)
  293. // 如果不需要每次登录都更新微信用户头像昵称, 下面4行代码可以屏蔽掉
  294. if ($isParty === true && !empty($partyData)) {
  295. $partyUserInfo = PartyService::partyUserInfo($partyData, true);
  296. $data = array_merge($data, $partyUserInfo);
  297. }
  298. // 更新用户记录
  299. $status = $userInfo->save($data) !== false;
  300. // 记录用户信息
  301. $this->userInfo = $userInfo;
  302. }
  303. /**
  304. * 记录登录态
  305. * @return bool
  306. * @throws BaseException
  307. */
  308. private function setSession(): bool
  309. {
  310. empty($this->userInfo) && throwError('未找到用户信息');
  311. // 登录的token
  312. $token = $this->getToken($this->getUserId());
  313. // 记录缓存, 30天
  314. Cache::set($token, [
  315. 'user' => $this->userInfo,
  316. 'store_id' => $this->storeId,
  317. 'is_login' => true,
  318. ], 86400 * 30);
  319. return true;
  320. }
  321. /**
  322. * 数据验证
  323. * @param array $data
  324. * @return void
  325. * @throws BaseException
  326. */
  327. private function validate(array $data): void
  328. {
  329. // 数据验证
  330. $validate = new ValidateLogin;
  331. if (!$validate->check($data)) {
  332. throwError($validate->getError());
  333. }
  334. // 验证短信验证码是否匹配
  335. // if (!CaptchaApi::checkSms($data['smsCode'], $data['mobile'])) {
  336. // throwError('短信验证码不正确');
  337. // }
  338. //todo 电子烟校验邮箱mobile的验证码是否匹配
  339. $mailCaptcha = new MailCaptcha();
  340. $mailCaptcha->checkCaptcha($data['smsCode'], $data['mobile']);
  341. }
  342. /**
  343. * 获取登录的token
  344. * @param int $userId
  345. * @return string
  346. */
  347. public function getToken(int $userId): string
  348. {
  349. static $token = '';
  350. if (empty($token)) {
  351. $token = $this->makeToken($userId);
  352. }
  353. return $token;
  354. }
  355. /**
  356. * 生成用户认证的token
  357. * @param int $userId
  358. * @return string
  359. */
  360. private function makeToken(int $userId): string
  361. {
  362. $storeId = $this->storeId;
  363. // 生成一个不会重复的随机字符串
  364. $guid = get_guid_v4();
  365. // 当前时间戳 (精确到毫秒)
  366. $timeStamp = microtime(true);
  367. // 自定义一个盐
  368. $salt = self::TOKEN_SALT;
  369. return md5("{$storeId}_{$timeStamp}_{$userId}_{$guid}_{$salt}");
  370. }
  371. }