Login.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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\api\service\passport;
  13. use think\facade\Cache;
  14. use yiovo\captcha\facade\CaptchaApi;
  15. use app\api\model\{User as UserModel, Setting as SettingModel};
  16. use app\api\service\{user\Oauth as OauthService, user\Avatar as AvatarService, passport\Party as PartyService};
  17. use app\api\validate\passport\Login as ValidateLogin;
  18. use app\common\service\BaseService;
  19. use app\common\enum\Setting as SettingEnum;
  20. use cores\exception\BaseException;
  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 $userInfo;
  33. // 用于生成token的自定义盐
  34. const TOKEN_SALT = 'user_salt';
  35. /**
  36. * 执行用户登录
  37. * @param array $data
  38. * @return bool
  39. * @throws BaseException
  40. * @throws \think\Exception
  41. * @throws \think\db\exception\DataNotFoundException
  42. * @throws \think\db\exception\DbException
  43. * @throws \think\db\exception\ModelNotFoundException
  44. */
  45. public function login(array $data): bool
  46. {
  47. // 数据验证
  48. $this->validate($data);
  49. // 自动登录注册
  50. $this->register($data);
  51. // 保存第三方用户信息
  52. $this->createUserOauth($this->getUserId(), $data['isParty'], $data['partyData']);
  53. // 记录登录态
  54. return $this->setSession();
  55. }
  56. /**
  57. * 快捷登录:微信小程序用户
  58. * @param array $form
  59. * @return bool
  60. * @throws BaseException
  61. * @throws \think\db\exception\DataNotFoundException
  62. * @throws \think\db\exception\DbException
  63. * @throws \think\db\exception\ModelNotFoundException
  64. * @throws \think\Exception
  65. */
  66. public function loginMpWx(array $form): bool
  67. {
  68. // 获取微信小程序登录态(session)
  69. $wxSession = PartyService::getMpWxSession($form['partyData']['code']);
  70. // 判断openid是否存在
  71. $userId = OauthService::getUserIdByOauthId($wxSession['openid'], 'MP-WEIXIN');
  72. // 获取用户信息
  73. $userInfo = !empty($userId) ? UserModel::detail($userId) : null;
  74. // 用户信息存在, 更新登录信息
  75. if (!empty($userInfo)) {
  76. // 更新用户登录信息
  77. $this->updateUser($userInfo, true, $form['partyData']);
  78. // 记录登录态
  79. return $this->setSession();
  80. }
  81. // 用户信息不存在 => 注册新用户 或者 跳转到绑定手机号页
  82. $setting = SettingModel::getItem(SettingEnum::REGISTER);
  83. // 后台设置了需强制绑定手机号, 返回前端isBindMobile, 跳转到手机号验证页
  84. if ($setting['isForceBindMpweixin']) {
  85. throwError('当前用户未绑定手机号', null, ['isBindMobile' => true]);
  86. }
  87. // 后台未开启强制绑定手机号, 直接保存新用户
  88. if (!$setting['isForceBindMpweixin']) {
  89. // 用户不存在: 创建一个新用户
  90. $this->createUser('', true, $form['partyData']);
  91. // 保存第三方用户信息
  92. $this->createUserOauth($this->getUserId(), true, $form['partyData']);
  93. }
  94. // 记录登录态
  95. return $this->setSession();
  96. }
  97. /**
  98. * 快捷登录:微信小程序用户
  99. * @param array $form
  100. * @return bool
  101. * @throws BaseException
  102. * @throws \think\db\exception\DataNotFoundException
  103. * @throws \think\db\exception\DbException
  104. * @throws \think\db\exception\ModelNotFoundException
  105. * @throws \think\Exception
  106. */
  107. public function loginMpWxMobile(array $form): bool
  108. {
  109. // 获取微信小程序登录态(session)
  110. $wxSession = PartyService::getMpWxSession($form['code']);
  111. // 解密encryptedData -> 拿到手机号
  112. $wxData = OauthService::wxDecryptData($wxSession['session_key'], $form['encryptedData'], $form['iv']);
  113. // 整理登录注册数据
  114. $loginData = [
  115. 'mobile' => $wxData['purePhoneNumber'],
  116. 'isParty' => $form['isParty'],
  117. 'partyData' => $form['partyData'],
  118. ];
  119. // 自动登录注册
  120. $this->register($loginData);
  121. // 保存第三方用户信息
  122. $this->createUserOauth($this->getUserId(), $loginData['isParty'], $loginData['partyData']);
  123. // 记录登录态
  124. return $this->setSession();
  125. }
  126. /**
  127. * 保存oauth信息(第三方用户信息)
  128. * @param int $userId 用户ID
  129. * @param bool $isParty 是否为第三方用户
  130. * @param array $partyData 第三方用户数据
  131. * @return void
  132. * @throws BaseException
  133. * @throws \think\db\exception\DataNotFoundException
  134. * @throws \think\db\exception\DbException
  135. * @throws \think\db\exception\ModelNotFoundException
  136. */
  137. private function createUserOauth(int $userId, bool $isParty, array $partyData = []): void
  138. {
  139. if ($isParty) {
  140. $Oauth = new PartyService;
  141. $Oauth->createUserOauth($userId, $partyData);
  142. }
  143. }
  144. /**
  145. * 当前登录的用户信息
  146. */
  147. public function getUserInfo(): ?UserModel
  148. {
  149. return $this->userInfo;
  150. }
  151. /**
  152. * 当前登录的用户ID
  153. * @return int
  154. */
  155. private function getUserId(): int
  156. {
  157. return (int)$this->getUserInfo()['user_id'];
  158. }
  159. /**
  160. * 自动登录注册
  161. * @param array $data
  162. * @return void
  163. * @throws \think\Exception
  164. * @throws \think\db\exception\DataNotFoundException
  165. * @throws \think\db\exception\DbException
  166. * @throws \think\db\exception\ModelNotFoundException
  167. */
  168. private function register(array $data): void
  169. {
  170. // 查询用户是否已存在
  171. // 用户存在: 更新用户登录信息
  172. $userInfo = UserModel::detail(['mobile' => $data['mobile']]);
  173. if ($userInfo) {
  174. $this->updateUser($userInfo, $data['isParty'], $data['partyData']);
  175. return;
  176. }
  177. // 用户不存在: 创建一个新用户
  178. $this->createUser($data['mobile'], $data['isParty'], $data['partyData']);
  179. }
  180. /**
  181. * 新增用户
  182. * @param string $mobile 手机号
  183. * @param bool $isParty 是否存在第三方用户信息
  184. * @param array $partyData 用户信息(第三方)
  185. * @return void
  186. * @throws \think\Exception
  187. * @throws \think\db\exception\DataNotFoundException
  188. * @throws \think\db\exception\DbException
  189. * @throws \think\db\exception\ModelNotFoundException
  190. */
  191. private function createUser(string $mobile, bool $isParty, array $partyData = []): void
  192. {
  193. // 用户信息
  194. $data = [
  195. 'mobile' => $mobile,
  196. 'nick_name' => !empty($mobile) ? hide_mobile($mobile) : '',
  197. 'platform' => getPlatform(),
  198. 'last_login_time' => time(),
  199. 'store_id' => $this->storeId
  200. ];
  201. // 写入用户信息(第三方)
  202. if ($isParty === true && !empty($partyData)) {
  203. $partyUserInfo = PartyService::partyUserInfo($partyData, true);
  204. $data = array_merge($data, $partyUserInfo);
  205. }
  206. // 新增用户记录
  207. $model = new UserModel;
  208. $status = $model->save($data);
  209. // 记录用户信息
  210. $this->userInfo = $model;
  211. }
  212. /**
  213. * 更新用户登录信息
  214. * @param UserModel $userInfo
  215. * @param bool $isParty 是否存在第三方用户信息
  216. * @param array $partyData 用户信息(第三方)
  217. * @return void
  218. */
  219. private function updateUser(UserModel $userInfo, bool $isParty, array $partyData = []): void
  220. {
  221. // 用户信息
  222. $data = [
  223. 'last_login_time' => time(),
  224. 'store_id' => $this->storeId
  225. ];
  226. // 写入用户信息(第三方)
  227. // 如果不需要每次登录都更新微信用户头像昵称, 下面4行代码可以屏蔽掉
  228. if ($isParty === true && !empty($partyData)) {
  229. $partyUserInfo = PartyService::partyUserInfo($partyData, true);
  230. $data = array_merge($data, $partyUserInfo);
  231. }
  232. // 更新用户记录
  233. $status = $userInfo->save($data) !== false;
  234. // 记录用户信息
  235. $this->userInfo = $userInfo;
  236. }
  237. /**
  238. * 记录登录态
  239. * @return bool
  240. * @throws BaseException
  241. */
  242. private function setSession(): bool
  243. {
  244. empty($this->userInfo) && throwError('未找到用户信息');
  245. // 登录的token
  246. $token = $this->getToken($this->getUserId());
  247. // 记录缓存, 30天
  248. Cache::set($token, [
  249. 'user' => $this->userInfo,
  250. 'store_id' => $this->storeId,
  251. 'is_login' => true,
  252. ], 86400 * 30);
  253. return true;
  254. }
  255. /**
  256. * 数据验证
  257. * @param array $data
  258. * @return void
  259. * @throws BaseException
  260. */
  261. private function validate(array $data): void
  262. {
  263. // 数据验证
  264. $validate = new ValidateLogin;
  265. if (!$validate->check($data)) {
  266. throwError($validate->getError());
  267. }
  268. // 验证短信验证码是否匹配
  269. // if (!CaptchaApi::checkSms($data['smsCode'], $data['mobile'])) {
  270. // throwError('短信验证码不正确');
  271. // }
  272. //todo 电子烟校验邮箱mobile的验证码是否匹配
  273. $mailCaptcha = new MailCaptcha();
  274. $mailCaptcha->checkCaptcha($data['smsCode'], $data['mobile']);
  275. }
  276. /**
  277. * 获取登录的token
  278. * @param int $userId
  279. * @return string
  280. */
  281. public function getToken(int $userId): string
  282. {
  283. static $token = '';
  284. if (empty($token)) {
  285. $token = $this->makeToken($userId);
  286. }
  287. return $token;
  288. }
  289. /**
  290. * 生成用户认证的token
  291. * @param int $userId
  292. * @return string
  293. */
  294. private function makeToken(int $userId): string
  295. {
  296. $storeId = $this->storeId;
  297. // 生成一个不会重复的随机字符串
  298. $guid = get_guid_v4();
  299. // 当前时间戳 (精确到毫秒)
  300. $timeStamp = microtime(true);
  301. // 自定义一个盐
  302. $salt = self::TOKEN_SALT;
  303. return md5("{$storeId}_{$timeStamp}_{$userId}_{$guid}_{$salt}");
  304. }
  305. }