Login.php 14 KB

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