Login.php 11 KB

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